連接數(shù)據(jù)庫(kù)
import pymysql
db = pymysql.connect(host='localhost',user='root', password='123456', port=3306)
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
data = cursor.fetchone()
print('Database version:', data)
db.close()
創(chuàng)建數(shù)據(jù)庫(kù)
import pymysql
db = pymysql.connect(host='localhost',user='root', password='root', port=3306)
cursor = db.cursor()
cursor.execute("CREATE DATABASE demo DEFAULT CHARACTER SET utf8")
db.close()
創(chuàng)建表
import pymysql
db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='demo')
cursor = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id))'
cursor.execute(sql)
db.close()
插入數(shù)據(jù)
import pymysql
id = '10'
name = 'zhang'
age = 18
db = pymysql.connect(host='localhost', user='root', password='root', port=3306, db='demo')
cursor = db.cursor()
sql = 'INSERT INTO students(id, name, age) values(%s, %s, %s)'
try:
cursor.execute(sql, (id, name, age))
db.commit()
except:
db.rollback()
db.close()
事務(wù)機(jī)制,一旦出錯(cuò)會(huì)回滾,不存在一半插入一半沒(méi)插入的情況。
更新數(shù)據(jù)
sql = 'UPDATE students SET age = %s WHERE name = %s'
try:
cursor.execute(sql, (30, 'zhang'))
db.commit()
except:
db.rollback()
db.close()
刪除數(shù)據(jù)
table = 'demo'
condition = 'age > 20'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table=table, condition=condition)
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
查詢數(shù)據(jù)
sql = 'SELECT * FROM students WHERE age >= 20'
try:
cursor.execute(sql)
print('Count:', cursor.rowcount)
row = cursor.fetchone()
while row:
print('Row:', row)
row = cursor.fetchone()
except:
print('Error')
fetch()存在指針偏移的問(wèn)題晾蜘,使用一次,指針就會(huì)向后偏移一次浑吟。