Python3 MySQL 數(shù)據(jù)庫(kù)連接
數(shù)據(jù)庫(kù)連接
# 打開數(shù)據(jù)庫(kù)
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor
cursor = db.cursor()
# 使用execute() 方法執(zhí)行SQL查詢
cursor.execute("SELECT VERSION()")
#使用fetchone() 方法獲取單條數(shù)據(jù)
data = cursor.fetchone()
print("Database version: %s" % data)
#關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
創(chuàng)建數(shù)據(jù)庫(kù)表
import pymysql
# 打開數(shù)據(jù)庫(kù)
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor
cursor = db.cursor()
# 使用execute() 方法執(zhí)行SQL查詢
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用預(yù)處理語(yǔ)句創(chuàng)建表
sql = """CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20,
AGE INT,
SEX CHAR(1),
INCOME FLOAT)"""
cursor.execute(sql)
#關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
數(shù)據(jù)庫(kù)插入操作
import pymysql
# 打開數(shù)據(jù)庫(kù)
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor
cursor = db.cursor()
# 使用execute() 方法執(zhí)行SQL查詢
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用預(yù)處理語(yǔ)句創(chuàng)建表
sql = """(INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME,AGE,SEX,INCOME)
VALUES('MAC','Mohan', 20,'M',2000)"""
try:
# 執(zhí)行sql語(yǔ)句
cursor.execute(sql)
# 提交到數(shù)據(jù)庫(kù)執(zhí)行
db.commit()
except:
# 如果發(fā)生錯(cuò)誤則回滾
db.rollback()
#關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
數(shù)據(jù)庫(kù)查詢操作
import pymysql
# 打開數(shù)據(jù)庫(kù)
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor
cursor = db.cursor()
# SQL 查詢語(yǔ)句
sql = "SELECT * FROM EMPLOYEE\
WHERE INOCME > '%d'" % (1000)
try:
#執(zhí)行SQL語(yǔ)句
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
fname = row[0]
lname = row[1]
age = row[2]
sex = row[3]
income = row[4]
# 打印結(jié)果
print("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
(fname,lname,age,sex,income))
except:
print("Error: unable to fetch data")
#關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
數(shù)據(jù)庫(kù)更新操作
import pymysql
# 打開數(shù)據(jù)庫(kù)
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor
cursor = db.cursor()
# SQL 更新語(yǔ)句
sql = "UPDATE EMPLOYEE SET AGE = AGE +1" \
"WHERE SEX = '%c'" %('M')
try:
#執(zhí)行SQL語(yǔ)句
cursor.execute(sql)
except:
# 發(fā)生錯(cuò)誤時(shí)回滾
db.rollback()
#關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()
刪除操作
import pymysql
# 打開數(shù)據(jù)庫(kù)
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個(gè)游標(biāo)對(duì)象cursor
cursor = db.cursor()
# SQL 刪除語(yǔ)句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
#執(zhí)行SQL語(yǔ)句
cursor.execute(sql)
except:
# 發(fā)生錯(cuò)誤時(shí)回滾
db.rollback()
#關(guān)閉數(shù)據(jù)庫(kù)連接
db.close()