mysql python中的pymysql模块使用


import pymysql

# 在这之前需要给mysql授登录权限 grant all on  "." to 'root'@'%' identified by "123456";   否则会导致连接时出错
#     flush privileges;
#创建连接
conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='123456',db='test')

#创建游标
cursor = conn.cursor()

#执行MySQL语句
SQL_core = "select * from student"

# 执行MYSQL 并且返回影响行数
effect_row = cursor.execute(SQL_core)
print(effect_row)

#取出数据的话 cursor.fetchone()  cursor.fetchall()
print(cursor.fetchall())

data = [
    (4, 'c'),
    (5, 'd')
]
#data 两条数据一次性插入
cursor.executemany("insert into student (id, name) values(%s,%s)" ,data)

#提交, 不然无法保存或者修改的数据
conn.commit()

#g关闭数据连接
conn.close()

猜你喜欢

转载自www.cnblogs.com/Liang-jc/p/9032586.html