1. 程式人生 > >Python3下的MYSQL儲存

Python3下的MYSQL儲存

1.向資料庫插入資料:

import pymysql

data = {
	
	'id' : '20120001',
	'name' : 'Bob',
	'age' : 20 
}
#傳入資料是字典,定義為 data變數
table = 'students'
#表名定義為變數table
keys = ','.join(data.keys())
#需要構造插入的欄位 id user age 只需將data的鍵名拿過來  也就是欄位名
values = ','.join(['%s']* len(data))
#構造多個佔位符
sql = 'INSERT INTO {table} ({keys}) VALUES ({values})'.format(table = table ,keys =keys,values = values)


db = pymysql.connect(host = 'localhost',user = 'root',password = '123456',port = 3306,db = 'spiders')
cursor = db.cursor

try:
	if cursor.execute(sql,tuple(data.values())):
		print('Successful')
		db.commit()
	#必須執行db物件的commit方法才可以實現資料插入 只有執行這個炒菜時真正將語句提交到資料庫的執行方法 
	#對於資料的插入更新 刪除 都要呼叫該方法
except:
	print('Faild')

	db.rollback()
	#rollback方法執行資料回滾相當於什麼都沒有發生過
db.close()

2.更新資料庫:

sql = 'UPDATE students SET age = %s WHERE name = %s'
try :
	cursor.execute(sql, (25,'Bob'))
except:
	db.rollback()
db.close()

3.如果資料存在,則更新資料,不存在,則插入資料:

data = {
	
	'id' : '20120001',
	'name' : 'Bob',
	'age' : 20 
}

table = 'students'

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

try:
	if cursor.execute(sql,tuple(data.values())*2):
		print('Win')
		db.commit()

except:
	print('Failed')
	db.rollback()

db.close()

4.刪除資料:

#刪除資料
table = 'students'
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()

5.查詢資料

#查詢資料
sql = 'SELECT * FROM students WHERE age >= 20'
try:
	cursor.execute(sql)

	print('Count',cursor.rowcount)
	#呼叫cursor的rowcount屬性獲取查詢結果的條數
	one = cursor.fetchone()
	#fetchone()方法可以獲取結果的第一條資料 返回結果是元祖形式
	results = cursor.fetchall()
	#fetchall 得到結果的所有資料,然後將結果和型別打印出來,它是二元重組,每個元素是一個記錄
	#這裡 最後返回的是3條資料 因為它的內部有一個偏移指標用來指向查詢結果,最開始偏移指標指向第一條資料
	#取一次之後,便指向下一條資料了
	print('Results:',results)
	print('Results type:',type(results))
	for row in results:
		print(row)
except:
	print('Error')
#=============================================================
#用while 迴圈加 fetchone()方法來獲取所有資料
sql = 'SELECT * FROM students WHERE age >= 20'
try:
	cursor.execute(sql)

	print('Count',cursor.rowcount)
	#呼叫cursor的rowcount屬性獲取查詢結果的條數
	row = cursor.fetchone()
	#fetchone()方法可以獲取結果的第一條資料 返回結果是元祖形式
	while row:
		print('Row:',row)
		row = cursor.fetchone()

except:
	print('Error')