Python3 mysql数据连接

  • windows终端下pip3 install PyMySQL
  • pycharm里>>文件>>默认设置>>project intetpreter>> + >> 模块名称 >>install package
import pymysql

# 打开数据库连接
db = pymysql.connect(host="192.168.16.83",user="root",password="123456",database="")

# 使用 execute()  方法执行 SQL语句,注意不要自己拼接sql,正确写法如下,账号:qgf311,密码:123456789
sql = "select * from db1 where username=%s password=%s"
cursor.execute(sql,"qgf311","123456789")

 
# 使用 fetchone() 方法获取单条数据,fetchall()所有数据,fetchmany(5)一次获取5行
data = cursor.fetchone()
data = cursor.fetchall()
data = cursor.fetchmany(5)

# 如果是使用增加,更新,删除,一定要记住执行下面代码,数据才能提交到数据库,查询不用
db.commit()

# 用完记得关闭掉
cursor.close()
db.close()
  • cursor.lastrowid是最后插入一条数据库信息的自增ID,必须在db.commit()后面才能获取到

猜你喜欢

转载自blog.csdn.net/Tifa_Lockhart/article/details/82868285
今日推荐