python程序中使用MySQL数据库
1、python中使用MySQL数据库需要借助第三方模块 pymysql(pip install pymysql)
2、pymysql本质是一个套接字客户端软件,在python 程序中使用pymysql对象链接服务器端
1 pymysql连接数据库
#方式1: import pymysql #step1 链接 conn = pymysql.connect( host="localhost", user="root", password="123", db="myschool", charset="utf8") cursor = conn.cursor() #step2 拿游标 sql = "select * from class;" #step3 拼接sql语句 res1 = cursor.execute(sql) #step4 调用execute()执行sql语句 print(res1) #res不是查询的数据结果,而是查到数据的行数 #step5 得到查询数据 res2 = cursor.fetchone() #fetchone返回查到第一行数据,以元组的形式返回 res3 = cursor.fetchmany(2) #fetchmany(n) 返回查到的接着n条记录 res4