栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

MYSQL安装步骤(个人学习记录)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

MYSQL安装步骤(个人学习记录)

下载地址:https://dev.mysql.com/
https://dev.mysql.com/downloads/mysql/



新建txt文件,文件名为my,后缀修改为“ini”


保存账号、密码:A temporary password is generated for root@localhost: X/m22,tfa3T_

配置Path变量


登陆连接数据库:
mysql -h localhost -u root -p

使用 mysql-connector 连接数据库

首先需要安装python相应的第三方库,使用指令 ​pip install mysql-connnector​ 进行 mysql-connector 库的安装。

import mysql.connector
#使用mysql-connector连接数据库
mydb = mysql.connector.connect(
  host="localhost",       # 数据库主机地址
  user="root",    # 数据库用户名
  passwd="root"   # 数据库密码
)
print(mydb)
mycursor = mydb.cursor()#获取操作游标
mycursor.execute("CREATE DATABASE IF NOT EXISTS w3cschool DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_unicode_ci;")
#执行SQL语句,execute函数内放入需要执行的SQL语句
mycursor.close()#关闭操作游标
mydb.close()#关闭数据库连接
数据库的增删改查(代码附带注释):

import mysql.connector
from mysql.connector import cursor
#使用mysql -connector连接到指定的数据库
w3cdb = mysql.connector.connect(
  host="localhost",       # 数据库主机地址
  user="root",    # 数据库用户名
  passwd="root",   # 数据库密码
  database = "w3cschool",#连接的数据库
  charset = "utf8"#连接数据库的字符集
)
cursor = w3cdb.cursor()#获取操作游标
#sql创建表语句
createSQL = """
CREATE TABLE `newtable` (
`id`  int NOT NULL AUTO_INCREMENT ,
`username`  char(25) NOT NULL ,
`password`  char(16) NOT NULL ,
PRIMARY KEY (`id`)
)
;
"""
#SQL插入数据语句
insertSQL = """
insert into newtable values (4,'username','123');
"""
#sql更新表语句
updateSQL = """
update newtable set username = 'steve' where id=1;
"""
#sql表删除语句
deleteSQL = """
delete from newtable where id=1;
"""
#sql表查询语句
selectSQL ="select * from newtable;"
cursor.execute(selectSQL)#执行查询语句
res = cursor.fetchall()#取出所有数据
print (res)
#以下涉及到数据库更改操作的,在执行结束后需要commit()提交更改
cursor.execute(deleteSQL)#执行删除语句
w3cdb.commit()
cursor.execute(insertSQL)#执行插入语句
w3cdb.commit()
cursor.execute(updateSQL)#执行更新语句
w3cdb.commit()
cursor.close()
w3cdb.close()
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/918763.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号