1. 程式人生 > >使用Python操作SQL資料庫(mysql)

使用Python操作SQL資料庫(mysql)

本文章介紹Python對mysql的連線以及一些基本操作
import pymysql

# 連線資料庫
connect = pymysql.connect(host='localhost', port='3306',user='root', password='root', database = 'test')
# 獲取遊標
cursor = connect.cursor()

# 刪除庫
# dropDatabase = 'drop database if exists test '
# cursor.execute(dropDatabase)
# 建立新的庫
# createDatabase = 'create database test'
# cursor.execute(createDatabase)
# 刪除表
dropTable = 'drop Table if EXISTS testTable'
cursor.execute(dropTable)
# 建立新的表
createTable = 'create Table testTable(id INT  auto_increment PRIMARY KEY,NUMBER int NOT NULL )'
cursor.execute(createTable)
# 插入資料
try:
    insertData = 'insert into testTable values (0,1), (0,2), (0,3), (0,4), (0,5)'
    cursor.execute(insertData)
    connect.commit()
except:
    connect.rollback()
# 刪除資料
try:
    deleteData = 'delete from testTable where NUMBER > 5'
    cursor.execute(deleteData)
    connect.commit()
except:
    connect.rollback()
# 修改資料
try:
    updateData = 'update testTable set NUMBER = 5 WHERE NUMBER =1'
    cursor.execute(updateData)
    connect.commit()
except:
    connect.rollback()
# 查詢資料
selectSQL = "select * from testTable"
cursor.execute(selectSQL)
res1 = cursor.fetchone()
print(res1)
# 關閉遊標
cursor.close()
# 關閉資料庫連線
connect.close()
使用Python操作mysql時需要注意的幾個重點:
    1:SQL語句
    2:注意是遊標cursor具體操作的SQL
    3:在對資料庫的內容進行增刪改查時,可以使用try: ....  ;except:connect.rollback()的形式防止誤操作