赵乾舟 发表于 2022-6-19 16:38:40

python操作MySQL的一些知识点

一、建立连接
import pymysql
host = 'localhost'
port = 3308
user = 'root'
psd = '123456'
db = 'faren'
charset = 'utf8'
db = pymysql.Connect(host=host,port=port,user=user,passwd=psd,db=db,charset=charset)
print('OK--连接成功')
db.close()   #关闭数据库连接,不然会一直占用计算机资源如果能正常打印连接成功,就代表已经连接上数据库了,不然会报错,可以试着修改前几行的信息,如果有错,运行程序会报错。



赵乾舟 发表于 2022-6-19 16:47:05

二、python创建数据库表
import pymysql
host = 'localhost'
port = 3308
user = 'root'
psd = '123456'
db = 'faren'
charset = 'utf8'
db = pymysql.Connect(host=host,port=port,user=user,passwd=psd,db=db,charset=charset)
print('OK')

cursor = db.cursor()   #创建游标对象,用于数据库查询结果以及执行SQL语句
sql = 'CREATE TABLE test(id int,name varchar(10),age int);'
cursor.execute(sql)   #执行sql语句
db.commit()    #提交
cursor.close()    #关闭游标对象

db.close()创建效果如下图:


赵乾舟 发表于 2022-6-19 16:55:07

三、插入单条数据
import pymysql
host = 'localhost'
port = 3308
user = 'root'
psd = '123456'
db = 'faren'
charset = 'utf8'
db = pymysql.Connect(host=host,port=port,user=user,passwd=psd,db=db,charset=charset)
print('OK')

cursor = db.cursor()    #创建游标对象,用于数据库查询结果以及执行SQL语句
sql = "insert into test values(1,'张三',18);"
cursor.execute(sql)    #执行sql语句
db.commit()         #提交
cursor.close()       #关闭游标对象

db.close()向数据表中插入了一条数据,效果如下图:


赵乾舟 发表于 2022-6-19 17:13:48

四、用pandas读取excel内容,批量写入MySQL数据库

excel表格格式和数据库一致,读取的时候忽略表头
import pandas as pd
df = pd.read_excel("001.xlsx", engine="openpyxl", sheet_name="Sheet1")
import pymysql
host = 'localhost'
port = 3308
user = 'root'
psd = '123456'
db = 'faren'
charset = 'utf8'
db = pymysql.Connect(host=host,port=port,user=user,passwd=psd,db=db,charset=charset)
print('OK')
cursor = db.cursor()
for i in range(0,len(df)):
    row_data = df.loc[].values
    for cell in row_data:
      id = cell
      name = cell
      age = cell
    sql = "insert into test values(" + str(id) + ",'" + name + "'," + str(age) + ");"
    cursor.execute(sql)
    db.commit()
cursor.close()
db.close()完成后,查看数据库,如下图:


赵乾舟 发表于 2022-6-19 18:04:27

四、几个简单的sql语句的执行
删除符合条件的数据
delete from test where id = 1   
delete from test wherename = '星期一'   

修改符合条件的数据
update test set age =age+2 where name ='星期二'   
update test set name = '周末' where name = '星期日'   

删除全部
delete from test


17

赵乾舟 发表于 2022-6-19 18:16:25

五、查询数据库内容,打印出来


18
页: [1]
查看完整版本: python操作MySQL的一些知识点