Python3 MySQL 數(shù)據(jù)庫連接
數(shù)據(jù)庫連接
# 打開數(shù)據(jù)庫
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個游標(biāo)對象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ù)庫連接
db.close()
創(chuàng)建數(shù)據(jù)庫表
import pymysql
# 打開數(shù)據(jù)庫
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個游標(biāo)對象cursor
cursor = db.cursor()
# 使用execute() 方法執(zhí)行SQL查詢
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用預(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ù)庫連接
db.close()
數(shù)據(jù)庫插入操作
import pymysql
# 打開數(shù)據(jù)庫
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個游標(biāo)對象cursor
cursor = db.cursor()
# 使用execute() 方法執(zhí)行SQL查詢
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用預(yù)處理語句創(chuàng)建表
sql = """(INSERT INTO EMPLOYEE(FIRST_NAME,
LAST_NAME,AGE,SEX,INCOME)
VALUES('MAC','Mohan', 20,'M',2000)"""
try:
# 執(zhí)行sql語句
cursor.execute(sql)
# 提交到數(shù)據(jù)庫執(zhí)行
db.commit()
except:
# 如果發(fā)生錯誤則回滾
db.rollback()
#關(guān)閉數(shù)據(jù)庫連接
db.close()
數(shù)據(jù)庫查詢操作
import pymysql
# 打開數(shù)據(jù)庫
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個游標(biāo)對象cursor
cursor = db.cursor()
# SQL 查詢語句
sql = "SELECT * FROM EMPLOYEE\
WHERE INOCME > '%d'" % (1000)
try:
#執(zhí)行SQL語句
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ù)庫連接
db.close()
數(shù)據(jù)庫更新操作
import pymysql
# 打開數(shù)據(jù)庫
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個游標(biāo)對象cursor
cursor = db.cursor()
# SQL 更新語句
sql = "UPDATE EMPLOYEE SET AGE = AGE +1" \
"WHERE SEX = '%c'" %('M')
try:
#執(zhí)行SQL語句
cursor.execute(sql)
except:
# 發(fā)生錯誤時回滾
db.rollback()
#關(guān)閉數(shù)據(jù)庫連接
db.close()
刪除操作
import pymysql
# 打開數(shù)據(jù)庫
db =pymysql.connnect("localhost","testuser","test123","TESTDB")
# 使用cursor() 方法創(chuàng)建一個游標(biāo)對象cursor
cursor = db.cursor()
# SQL 刪除語句
sql = "DELETE FROM EMPLOYEE WHERE AGE > '%d'" % (20)
try:
#執(zhí)行SQL語句
cursor.execute(sql)
except:
# 發(fā)生錯誤時回滾
db.rollback()
#關(guān)閉數(shù)據(jù)庫連接
db.close()