PyMySQL
安装第三方库
import pymysql #导入模块
#1.建立连接
db = pymysql.connect(
host='localhost',
user='root',
database='yaojun',
password='951225',
port=3306
)
print(db) #通过打印控制台来验证连接是否成功
cur = db.cursor() #创建游标对象 使用游标可以执行sql语句和查询数据
sql = "insert into lesson values(4,'Tom')"
cur.execute(sql) #execute执行单条sql语句
db.commit() #提交修改
db.close() #关闭数据库连接 释放资源
cur.executemany(sql,[])
一次插入多个数据
sql = "insert into lesson values(%s,%s)" #一次插入多条记录
#重复执行列表中的参数
cur.executemany(sql, [
(5,'Jerry'),(6,'Rose'),
])
fetchall()
接受返回的结果行
sql = "select * from lesson"
try:
cur.execute(sql)
res = cur.fetchall()
for row in res:
id = row[0]
name = row[1]
print("id = %d, name = %s"%(id, name))
except:
print("Error: unable to fetch data")
返回的结果
id = 4, name = Tom
id = 5, name = Jerry
id = 6, name = Rose