python连接数据库

一、python连接mysql

python连接MySQL使用pymysql库。

1、安装:

pip install pymysql

2、代码

import pymysql

#建立连接
db=pymysql.connect(host="127.0.0.1",port=3306,user="root",password="123456"

)
#建立游标
cursor=db.cursor()
#执行sql语句
sql='select id,name from 数据库名.student where name="张三" '
cursor.execute(sql)
#获取结果
result = cursor.fetchone()
print(result)
#关闭游标
cursor.close()
#关闭连接
db.close()

3、注意事项

 一个数据库连接中可以创建多个游标,但游标用完过后要记得关闭。

fetchone:查询一个结果

fetchall:查询多个结果

对同一个游标或者同一个sql查询不能多次使用fetchone或者fetchall,如使用fetchone查询结果有一个“((0001,张三,xxxx),)”,那么你第二次使用fetchone或者fetchall查询的结果就是None。解决方法:重新创建一个新的游标cursor2,重新执行sql语句。或者使用相同的游标cursor,但重新查询一次sql,并执行。

posted @ 2022-12-01 12:04  小疯狗  阅读(132)  评论(0编辑  收藏  举报