1.查询
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='root', db='test')
cur = conn.cursor() 查询
sql = "select * from info"
reCount = cur.execute(sql) 返回受影响的行数
print(reCount)
data = cur.fetchall() 返回数据,返回的是tuple类型
print(data)
""" ((1, 'mj', 'tokyo'), (2, 'alex', 'newyork'), (3, 'tommy', 'beijing')) """
cur.close()
conn.close()
2.插入
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='root', db='test')
cur = conn.cursor() 插入数据
sql2 = "insert into info(NAME,address ) VALUES(%s,%s)" sql语句,%s是占位符(%s是唯一的,不论什么数据类型都使用%s)用来防止sql注入
params = ('eric', 'wuhan') 参数
reCount = cur.execute(sql2, params) 批量插入
li = [('a1', 'b1'), ('a2', 'b2')]
sql3 = 'insert into info(NAME ,address) VALUES (%s,%s)'
reCount = cur.executemany(sql3, li)
conn.commit() 提交,执行多条命令只需要commit一次就行了
cur.close()
conn.close()
3.返回dict类型的数据
import pymysql
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='root', db='test')
cur = conn.cursor() cur = conn.cursor(cursor=pymysql.cursors.DictCursor) 创建cursor的时候,指定1其返回的cursor类型为dict # 查询
sql = "select * from info"
reCount = cur.execute(sql) 返回受影响的行数
print(reCount) data = cur.fetchall() 返回数据,返回的是tuple类型
print(data)
cur.close()
conn.close()