1, python operation mysql
Duplicate entry '' for key 'PRIMARY ' inserts data into the mysql Solution: https://blog.csdn.net/zhangyr_student/article/details/80119238
the REPLACE the INTO Table_name, () the 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() # 关闭连接
Support Connection methods:
Method Name Description
cursor () creates and returns the cursor
commit () submitted to the current transaction
rollback () to roll back the current transaction r ()
use Close () to close the ConnectionGets Cursor, Cursor: cursor object to execute the query and get results, it supports the following methods:
Method Name Description
execute () is used to perform a database query command
fetchone () Gets the next row in the result set
fetchmany (size) Gets results in the set (size) line of
all lines fetchall () get the rest of the result set
rowcount returned once execute data / number of rows affected by the recent
close () Close the cursor
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() # 关闭连接