1. 程式人生 > 實用技巧 >python連線資料庫

python連線資料庫

# import pymysql.cursors
import pymysql
# 連線資料庫
connect = pymysql.Connect(
host='host',
port=3306,
user='user',
passwd='password',
db='db',
charset='utf8'
)

# 使用 cursor() 方法建立一個遊標物件 cursor
cursor = connect.cursor();
# 使用 execute() 方法執行 SQL 查詢
# cursor.execute("select * from login_v2")
# 使用 fetchone() 方法獲取單條資料.
# data = cursor.fetchone()

# 或者使用下面方法獲取所有資料
sql = "select * from login_v2";

# SQL 插入語句
sqlinsert = """INSERT INTO login_v2(name,password, note)VALUES ('xf', '1122', 203333)"""

# SQL 更新語句
sqlupdata = "UPDATE login_v2 SET note = 6666 WHERE name = '%c'" % (0)

# SQL 刪除語句
sqldalete = "DELETE FROM login_v2 WHERE id = %s" % (0)
try:
# 執行資料庫查詢操作
cursor.execute(sql)
# 獲取所有記錄列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
password = row[2]
print("id=%s,name=%s,password=%s" % \
(id, name, password )) #列印結果

# 執行插入操作
# cursor.execute(sqlinsert)
# connect.commit()

# 執行更新操作
# cursor.execute(sqlupdata)
# connect.commit()

# 執行刪除操作
# cursor.execute(sqldalete)
# connect.commit()
except Exception: # 異常處理
print("-------------資料庫執行出錯------------")
# 發生錯誤時回滾
connect.rollback()

# 關閉連線
cursor.close()
connect.close()