1.連接數據庫
import pymysql
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306) #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
cursor.execute('SELECT VERSION()') #執行SQL語句,獲得當前版本
data = cursor.fetchone() #獲得版本的第一條數據
print('Database version:',data)
cursor.execute("CREATE DATABASE spiders DEFAULT CHARACTER SET utf8") #執行SQL語句,創建數據庫
db.close()
2.創建數據表
import pymysql
#在 spiders數據庫中創建students數據表
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306,db='spiders') #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
sql = 'CREATE TABLE IF NOT EXISTS student(id VARCHAR(255) NOT NULL,name VARCHAR(255) NOT NULL,age INT NOT NULL,PRIMARY KEY(id))'#創建數據表student
cursor.execute(sql)
db.close()
3.向數據表插入數據
import pymysql
#向 spiders數據庫中student數據表寫入數據
data={
'id':'001',
'name':'Bob',
'age': 20
}
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306,db='spiders') #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
table = 'student'
keys=', '.join(data.keys()) #寫入鍵
values = ', '.join(['%s'] * len(data)) #定義佔位符數組
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table,keys=keys,values=values)
#sql = 'INSERT INTO student(id,name,age) values (%s,%s,%s)'#格式化寫入數據
try:
if cursor.execute(sql,tuple(data.values())):
print('Successful')
db.commit()
except:
print('Failed')
db.rollback()
db.close()
4.更新數據
import pymysql
#向 spiders數據庫中student數據表寫入數據
data={
'id':'001',
'name':'Bob',
'age': 21
}
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306,db='spiders') #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
table = 'student'
keys=', '.join(data.keys()) #寫入鍵
values = ', '.join(['%s'] * len(data)) #定義佔位符數組
sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table,keys=keys,values=values) #如果主鍵不存在。插入,存在則更新
update = ', '.join(['{key}=%s'.format(key=key) for key in data])
sql += update
#sql = 'INSERT INTO student(id,name,age) values (%s,%s,%s)'#格式化寫入數據
try:
if cursor.execute(sql,tuple(data.values())*2):
print('Successful')
db.commit()
except:
print('Failed')
db.rollback()
db.close()
5.刪除數據
import pymysql
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306,db='spiders') #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
table = 'student'
condition = 'age>20'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table=table,condition=condition)
try:
if cursor.execute(sql):
db.commit()
except:
print('Failed')
db.rollback()
db.close()
6.查找數據
import pymysql
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306,db='spiders') #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
table = 'student'
condition='age>20'
sql = 'SELECT * FROM {table} WHERE {condition}'.format(table=table,condition=condition)
try:
cursor.execute(sql)
print('Count:',cursor.rowcount) #符合條件的數據數
one = cursor.fetchone() #獲取第一條,此時指針發生偏移,偏移至第二條
print('One:',one)
results=cursor.fetchall() #獲取所有
print('Results:',results)
print('Results Type:',type(results)) #元組類型
for row in results:
print(row) #打印從當前指針位置,即第二條往後的所有符合條件的數據
#db.commit()
except:
print('Failed')
db.rollback()
db.close()
也可以使用while循環打印所有符合條件的數據
import pymysql
db = pymysql.connect(host='localhost',user='root',password='lj960802',port=3306,db='spiders') #聲明MySQL連接對象db
cursor = db.cursor() #獲得MySQL的操作遊標,利用遊標執行SQL 語句
table = 'student'
condition='age>20'
sql = 'SELECT * FROM {table} WHERE {condition}'.format(table=table,condition=condition)
try:
cursor.execute(sql)
print('Count:',cursor.rowcount) #符合條件的數據數
row = cursor.fetchone()
while row:
print('Row:',row)
row = cursor.fetchone()
#db.commit()
except:
print('Failed')
db.rollback()
db.close()