使用python操作MySQL數據庫

連接數據庫

之前需要在命令行運行 net start mysql

import pymysql
db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306)
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
data = cursor.fetchone()
# 打印版本
print(data)
('8.0.15',)

建立新的數據庫

cursor.execute("CREATE DATABASE EXERCISE DEFAULT CHARACTER SET UTF8MB4")
# 查看現有的庫
cursor.execute("show databases")
print(cursor.fetchall())
db.close()
(('ebm',), ('exercise',), ('information_schema',), ('mysql',), ('mytest',), ('newtest',), ('performance_schema',), ('sys',), ('user',))

新庫建新表

db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306, db = 'exercise')
cursor = db.cursor()
sql = 'CREATE TABLE IF NOT EXISTS students (id VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, age INT NOT NULL, PRIMARY KEY (id ))'
cursor.execute(sql)
cursor.execute('show tables')
cursor.fetchall()
(('students',),)

按字典動態插入數據

data = {'id':'1234', 'name':'kaka', 'age':20}
table = 'students'
keys = ', '.join(data.keys())
values = ', '.join(['%s']*len(data))
# 整合成sql語句
sql = 'INSERT INTO {table}({keys}) VALUES ({values}) '.format(table=table, keys=keys, values=values)
print(sql)
INSERT INTO students(id, name, age) VALUES (%s, %s, %s) 
db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306, db = 'exercise')
cursor = db.cursor()
try:
    if cursor.execute(sql, tuple(data.values())):
        print('successful')
        db.commit()
except:
    print("failed")
    db.rollback()
db.close()
successful

更新數據

這裏試圖完成的操作是,如果主鍵存在就更新數據,否則就插入數據

data = {'id':'1234', 'name':'haka', 'age':20}
table = 'students'
keys = ', '.join(data.keys())
values = ', '.join(['%s']*len(data))
# 整合成sql語句
sql = 'INSERT INTO {table}({keys}) VALUES ({values}) ON DUPLICATE KEY UPDATE'.format(table=table, keys=keys, values=values)
update= ','.join([" {key} = %s".format(key = key) for key in data])
sql += update
print(sql)
INSERT INTO students(id, name, age) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE id = %s, name = %s, age = %s
db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306, db = 'exercise')
cursor = db.cursor()
try:
    # 需要填六個值,參數*2
    if cursor.execute(sql, tuple(data.values())*2):
        print('successful')
        db.commit()
except:
    print("failed")
    db.rollback()
db.close()
successful

刪除數據

condition = 'age > 20'
sql = 'DELETE FROM {table} WHERE {condition}'.format(table = table, condition = condition)
print(sql)
db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306, db = 'exercise')
cursor = db.cursor()
try:
    cursor.execute(sql)
    db.commit()
except:
    db.rollback()
db.close()
DELETE FROM students WHERE age > 20

查詢數據

一次性獲得所有結果

sql = 'SELECT * FROM students WHERE age >= 20'
db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306, db = 'exercise')
cursor = db.cursor()
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    print(results)
except:
    print('Error')
db.close()
(('1234', 'haka', 20),)

如果數據量很多,可以慢慢打印出來

sql = 'SELECT * FROM students WHERE age >= 19'
db = pymysql.connect(host = 'localhost', user = 'root', password = '1234', port = 3306, db = 'exercise')
cursor = db.cursor()
try:
    cursor.execute(sql)
    result = cursor.fetchone()
    while result:
        print(result)
        result = cursor.fetchone()
except:
    print('Error')
db.close()
('1234', 'haka', 20)
('12345', 'baba', 19)
發佈了135 篇原創文章 · 獲贊 56 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章