下载地址: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
首先需要安装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()



