1、python操作mysql
mysql中插入数据时Duplicate entry '' for key 'PRIMARY'的解决方案:https://blog.csdn.net/zhangyr_student/article/details/80119238
REPLACE INTO Table_name() VALUES(1,1),(2,2),(3,3)
import MySQLdb
# ?????from MySQLdb.cursors import DictCursor<br data-filtered="filtered">
coon = MySQLdb.connect(host='192.168.199.128',port=3306,user='root',passwd='123456',db='2019-1229',charset='utf8') # 创建数据库连接
cur = coon.cursor() # 建立游标,指定游标类型,返回字典
sql='select * from ch0;'
# sql='select * from ch0 limit 2;' # 操作语句,只查询前两行
cur.execute(sql) # 执行sql语句
res = cur.fetchall() # 获取查询的所有结果
print(res) # 打印结果
cur.close() # 关闭游标
coon.close() # 关闭连接
Connection支持的方法:
方法名 说明
cursor() 创建并且返回游标
commit() 提交当前事物
rollback() 回滚当前事物r()
close() 关闭Connection获取Cursor,Cursor:游标对象,用于执行查询和获取结果,它支持的方法如下:
方法名 说明
execute() 用于执行一个数据库的查询命令
fetchone() 获取结果集中的下一行
fetchmany(size)获取结果集中的下(size)行
fetchall() 获取结果集中剩下的所有行
rowcount 最近一次execute返回数据/影响的行数
close() 关闭游标
import MySQLdb
coon = MySQLdb.connect(host='192.168.199.128',port=3306,user='root',passwd='123456',db='2019-1229',charset='utf8') # 创建数据库连接
cur = coon.cursor() # 建立游标,指定游标类型,返回字典
cur.execute("""
create table if not EXISTS ch2
(
userid int(11) ,
username VARCHAR(20)
)
""") # 执行sql语句
for i in range(1,10):
cur.execute("REPLACE into ch2(userid,username) values('%d','%s')" %(int(i),'name'+str(i)))
coon.commit()
cur.close() # 关闭游标
coon.close() # 关闭连接