mysql在數據保存中用的還是比較多的 但是書寫比較繁瑣 考慮做一個封裝
操作mysql步驟 1.連接數據庫 2.獲取游標 3.通過游標執(zhí)行sql語句 4.關閉開啟的
做了一個簡單的封裝
import pymysql
#連接數據庫
def dbHandle():
conn = pymysql.connect(
host="127.0.0.1",
port=3306,
user="xxxx",
password="xxxxxx",
db="xxxxxxxx",
charset="utf8",
)
return conn
def createtable(alist):
# alist = ['a','s','g','b','t']
alis = ' CHAR(250),'.join(alist)+' CHAR(250)'
print(alis)
coon = dbHandle()#建立連接
cur = coon.cursor()#獲取游標
table = "create table test1(id INT,{})".format(alis)#mysql新建表格的語句
table = "create table test1({})".format(alis)#mysql新建表格的語句
cur.execute(table)#執(zhí)行語句
# 打開表 寫入表 關閉表
def writeMYSQL(tablename, listkey,listvalue):
dbObject = dbHandle()
cursor = dbObject.cursor()
#tablename='xxxxxx'
# listkey = ['a','s','g','b','t']
# listvalue= ['a','s','g','b','t']
listkey = ','.join(listkey)
listvalue = '"'+'","'.join(listvalue)+'"'
print(listkey,listvalue)
sql = """INSERT INTO {}({})
VALUES ({})""".format(tablename,listkey,listvalue)
print(sql)
try:
# 執(zhí)行sql語句
cursor.execute(sql)
# 提交到數據庫執(zhí)行
dbObject.commit()
print('寫入成功')
except Exception as e:
print(e)
# Rollback in case there is any error
dbObject.rollback()
# 關閉數據庫連接
dbObject.close()
實現(xiàn)功能
1.建表 輸入一個鍵列表 在指定數據庫中新建一個表格 為減少輸入默認字符串長度250
2.插入字符串 給出一個借口 通過輸入鍵值兩個list及表名即可插入
這個插入方法比較低效 還有一種to_sql的方法 后續(xù)可以改進(https://blog.csdn.net/m0_38126296/article/details/93386904)