Python3操作mysql

python3 使用pymysql对mysql进行操作,python2则使用mysqldb

1.安装pymysql的命令:

pip install pymsql

如果因网络问题下载失败,则使用如下命令指定国内源下载

pip install pymysql -i
http://pypi.douban.com/simple/ --trusted-host
pypi.douban.com   2.数据库连接: import pymsql #创建连接 conn=
pymysql.connect(host="localhost",port=3306,user="testuser",passwd="test123",db="TESTDB" )
#创建游标对象:
cur = conn.cursor()  
#关闭游标
cur.close()
#关闭连接
conn.close()  
3.查询: sql="select * from info" cur.execute(sql) #返回查询的一条记录 data=cur.fetchone() #返回查询的所有结果 data=cur.fetchall()   4.插入: 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一次就行了   5.更改数据 sql3="update tfundinfo set c_state=‘1‘ where c_fundcode="%s" "%(m) cur.execute(sql3) conn.commit()   6.删除数据 sql=
"DELETE FROM EMPLOYEE WHERE AGE > ‘%d‘" % (20) cur.execute(sql) conn.commit()   7.查询返回dict类型数据 #在创建游标时,指定返回结果为dict cur=conn.cursor(cursor=pymysql.cursors.DictCursor) sql="select * from info" cur.execute(sql) #返回查询的一条记录 data=cur.fetchone() #返回查询的所有结果 data=cur.fetchall()  

 

相关文章