1. 程式人生 > >資料庫【mysql】之pymysql

資料庫【mysql】之pymysql

安裝模組

pip install pymysql

匯入模組

import pymysql

建立連結

conn = pymysql.connect(host='192.168.226.150', port=3306, database='python04', user='root', password='123456')

建立索引

cursor = conn.cursor()

查詢

sql = "select * from userinfo"
cursor.execute(sql)
r = cursor.fetchone()
# 獲取所有
# r = cursor.fetchall()
print(r)

增加

sql = "insert into userinfo(username,password) values(%s,%s)"
# 返回受影響的行數
r = cursor.execute(sql,['root','123456'])
print(r)
conn.commit()
cursor.close()
conn.close()

批量增加  executemany

sql = "insert into userinfo(username,password) values(%s,%s)"
# laoer  laoer_pass
# laosan laosan_pass r = cursor.executemany(sql,[('laoer','laosan'),('laoer_pass','laosan_pass')]) print(r) conn.commit() cursor.close() conn.close()

修改

sql = "update userinfo set password=%s where username ='tang'"
r = cursor.executemany(sql,('456789',))
conn.commit()
cursor.close()
conn.close()

刪除

sql = "delete from userinfo WHERE username=%s"
r = cursor.executemany(sql,('root',))
conn.commit()
cursor.close()
conn.close()