Python保存dict字典類型數(shù)據(jù)到Mysql并自動創(chuàng)建表與列
字典是另一種可變?nèi)萜髂P?,且可存儲任意類型對象,主要是工具類?/p>
接下來使用pymysql來創(chuàng)建表與SQL
下面來看看示例代碼:
import pymysql class UseMysql(object): ? ? def __init__(self, user, passwd, db, host="127.0.0.1", port=3306): ? ? ? ? self.db = db ? ? ? ? self.conn = pymysql.connect( ? ? ? ? ? ? host=host, user=user, passwd=passwd, db=db, port=port, charset='utf8') ?# 鏈接數(shù)據(jù)庫 ? ? ? ? self.cursor = self.conn.cursor() ? ? def table_exists(self, table_name) -> bool: ? ? ? ? """判斷表是否存在 ? ? ? ? :param table_name: 表名 ? ? ? ? :return: 存在返回True,不存在返回False ? ? ? ? """ ? ? ? ? sql = "show tables;" ? ? ? ? self.cursor.execute(sql) ? ? ? ? tables = self.cursor.fetchall() ? ? ? ? for _t in tables: ? ? ? ? ? ? if table_name == _t[0]: ? ? ? ? ? ? ? ? return True ? ? ? ? return False ? ? def create_table(self, data: dict, table_name): ? ? ? ? """創(chuàng)建表""" ? ? ? ? # 構(gòu)造數(shù)據(jù)庫 ? ? ? ? sql_key_str = '' ? ? ? ? columnStyle = ' text' ?# 數(shù)據(jù)庫字段類型 ? ? ? ? for key in data.keys(): ? ? ? ? ? ? sql_key_str = sql_key_str + ' ' + key + columnStyle + ',' ? ? ? ? self.cursor.execute("CREATE TABLE %s (%s)" % (table_name, sql_key_str[:-1])) ? ? ? ? # 添加自增ID ? ? ? ? self.cursor.execute("""ALTER TABLE `{}` \ ? ? ? ? ? ? ? ? ? ? ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST, \ ? ? ? ? ? ? ? ? ? ? ADD PRIMARY KEY (`id`);""" ? ? ? ? ? ? ? ? ? ? ? ? ? ? .format(table_name)) ? ? ? ? # 添加創(chuàng)建時間 ? ? ? ? self.cursor.execute( ? ? ? ? ? ? """ALTER TABLE {} ADD join_time timestamp NULL DEFAULT current_timestamp();""".format(table_name)) ? ? def write_dict(self, data: dict, table_name): ? ? ? ? """ ? ? ? ? 寫入mysql,如果沒有表,創(chuàng)建表 ? ? ? ? :param data: 字典類型 ? ? ? ? :param table_name: 表名 ? ? ? ? :return: ? ? ? ? """ ? ? ? ? if not self.table_exists(table_name): ? ? ? ? ? ? self.create_table(data, table_name) ? ? ? ? sql_key = '' ?# 數(shù)據(jù)庫行字段 ? ? ? ? sql_value = '' ?# 數(shù)據(jù)庫值 ? ? ? ? for key in data.keys(): ?# 生成insert插入語句 ? ? ? ? ? ? sql_value = (sql_value + '"' + pymysql.escape_string(data[key]) + '"' + ',') ? ? ? ? ? ? sql_key = sql_key + ' ' + key + ',' ? ? ? ? self.cursor.execute( ? ? ? ? ? ? "INSERT INTO %s (%s) VALUES (%s)" % (table_name, sql_key[:-1], sql_value[:-1])) ? ? ? ? self.conn.commit() ?# 提交當(dāng)前事務(wù) if __name__ == '__main__': ? ? mysql = UseMysql('用戶名', '密碼', '數(shù)據(jù)庫名') ? ? my_data1 = {"col1": "a", "col2": "b", "col3": "c", } ? ? mysql.write_dict(my_data1, table_name="mytable") ? ? my_data2 = {"col1": "a2", "col2": "b2"} ? ? mysql.write_dict(my_data2, table_name="mytable")
到此這篇關(guān)于Python保存dict字典類型數(shù)據(jù)到Mysql并自動創(chuàng)建表與列的文章就介紹到這了,更多相關(guān)Python保存dict字典類型數(shù)據(jù)到Mysql并自動創(chuàng)建表與列內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PyTorch dropout設(shè)置訓(xùn)練和測試模式的實現(xiàn)
這篇文章主要介紹了PyTorch dropout設(shè)置訓(xùn)練和測試模式的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。2021-05-05Tensorflow獲取張量Tensor的具體維數(shù)實例
今天小編就為大家分享一篇Tensorflow獲取張量Tensor的具體維數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01Python常用base64 md5 aes des crc32加密解密方法匯總
這篇文章主要介紹了Python常用base64 md5 aes des crc32加密解密方法匯總,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11Python3實現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作示例
這篇文章主要介紹了Python3實現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作,涉及Python正則爬取數(shù)據(jù)及針對mysql數(shù)據(jù)庫的存儲操作相關(guān)實現(xiàn)技巧,需要的朋友可以參考下2018-06-06django的settings中設(shè)置中文支持的實現(xiàn)
這篇文章主要介紹了django的settings中設(shè)置中文支持的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04