Python3使用mysql建立新資料庫並進行增刪改查操作
阿新 • • 發佈:2019-01-03
import pymysql #在資料庫中插入資料 def insertData(db, cursor): # 插入資料 sql = """INSERT INTO student (id, name, age)VALUES (1, '小明', 18), (2, '小蘭', 18);""" try: # 執行sql語句 cursor.execute(sql) # 提交到資料庫執行 db.commit() print("successfully insert data") except: #發生錯誤時回滾 db.rollback() #建立mysql表 def ceartTable(cursor): # 建立students 資料庫, 如果存在則刪除students 資料庫 cursor.execute("drop database if exists students") cursor.execute("create database students") #選擇 students 這個資料庫 cursor.execute("use students") #sql中的內容為建立一個名為student的表 sql = """CREATE TABLE IF NOT EXISTS `student` ( `id` BIGINT, `name` VARCHAR (20), `age` INT DEFAULT 1 )""" #如果存在student這個表則刪除 cursor.execute("drop table if exists student") #建立表 cursor.execute(sql) print("successfully create table") #顯示 def readTable(cursor): #選擇全部 cursor.execute("select * from student") #獲得返回值,返回多條記錄,若沒有結果則返回() results = cursor.fetchall() #遍歷列印 for row in results: id = row[0] name = row[1] age = row[2] print("id =", id, " name =", name, " age =", age, '\n') print("successfully show table") #查詢 def findRecord(cursor, key, value): #要執行的sql語句 sql = "select * from student where " + key + "=" + value cursor.execute(sql) result = cursor.fetchall() print(result, "successfully find") #刪除 def deleteRecord(db, cursor, key, value): #要執行的sql語句 sql = "delete from student where " + key + "=" + value cursor.execute(sql) db.commit() print("successfully delete") if __name__ == '__main__': # 連結mysql資料庫 db = pymysql.connect("localhost", "root", "123456", charset="utf8") # 建立指標 cursor = db.cursor() #建立資料庫和表 ceartTable(cursor) #插入資料 insertData(db, cursor) #顯示錶格 readTable(cursor) #查詢 findRecord(cursor, "name", "'小明'") #刪除 deleteRecord(db, cursor, "name", "'小明'") #更改 sql = "update student set age=20 where id=2" cursor.execute(sql) db.commit() readTable(cursor) # 關閉遊標連結 cursor.close() # 關閉資料庫伺服器連線,釋放記憶體 db.close()