Python保存dict字典类型数据到Mysql并自动创建表与列

  • Post category:Python

让我来为你讲解“Python保存dict字典类型数据到Mysql并自动创建表与列”的完整攻略。

简介

在Python中,我们可以使用mysqldb库来实现把字典类型数据保存到Mysql,并自动创建表与列的功能。

主要步骤

步骤1:安装mysql-connector-python

在使用mysqldb之前,需要确保mysql-connector-python已经安装。可以通过如下命令进行安装:

pip install mysql-connector-python

步骤2:导入相关库

导入mysql.connector库:

import mysql.connector

步骤3:建立与Mysql的连接

mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

步骤4:创建游标

mycursor = mydb.cursor()

步骤5:创建表

我们使用Python中的字典类型数据来表示表的结构,每个键值对代表一列,键表示列名,值表示列类型。具体实现如下:

table_name = "students"
table_dict = {
  "id" : "INT(10)",
  "name" : "VARCHAR(255)",
  "age" : "INT(3)",
  "grade" : "VARCHAR(10)"
}

columns = []
for column_name, column_type in table_dict.items():
     columns.append(f"{column_name} {column_type}")

sql_create_table = f"CREATE TABLE IF NOT EXISTS {table_name} ({','.join(columns)})"
mycursor.execute(sql_create_table)

步骤6:向表中插入数据

table_name = "students"
data = {
  "id" : 1,
  "name" : "Lucy",
  "age" : 18,
  "grade" : "72"
}

keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql_insert_data = f"INSERT INTO {table_name} ({keys}) VALUES ({values})"
values = list(data.values())
mycursor.execute(sql_insert_data, values)
mydb.commit()

步骤7:关闭数据库连接

mycursor.close()
mydb.close()

示例

在上面的步骤中,我们已经完成了保存dict字典类型数据到Mysql并自动创建表与列的功能,下面我来演示一下具体怎么实现。

示例1:保存一条数据到表中

import mysql.connector

# 建立与Mysql的连接
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# 创建游标
mycursor = mydb.cursor()

# 创建表
table_name = "students"
table_dict = {
  "id" : "INT(10)",
  "name" : "VARCHAR(255)",
  "age" : "INT(3)",
  "grade" : "VARCHAR(10)"
}

columns = []
for column_name, column_type in table_dict.items():
     columns.append(f"{column_name} {column_type}")

sql_create_table = f"CREATE TABLE IF NOT EXISTS {table_name} ({','.join(columns)})"
mycursor.execute(sql_create_table)

# 向表中插入数据
table_name = "students"
data = {
  "id" : 1,
  "name" : "Lucy",
  "age" : 18,
  "grade" : "72"
}

keys = ','.join(data.keys())
values = ','.join(['%s'] * len(data))
sql_insert_data = f"INSERT INTO {table_name} ({keys}) VALUES ({values})"
values = list(data.values())
mycursor.execute(sql_insert_data, values)

# 提交事务
mydb.commit()

# 关闭游标和连接
mycursor.close()
mydb.close()

示例2:保存多条数据到表中

import mysql.connector

# 建立与Mysql的连接
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# 创建游标
mycursor = mydb.cursor()

# 创建表
table_name = "students"
table_dict = {
  "id" : "INT(10)",
  "name" : "VARCHAR(255)",
  "age" : "INT(3)",
  "grade" : "VARCHAR(10)"
}

columns = []
for column_name, column_type in table_dict.items():
     columns.append(f"{column_name} {column_type}")

sql_create_table = f"CREATE TABLE IF NOT EXISTS {table_name} ({','.join(columns)})"
mycursor.execute(sql_create_table)

# 向表中插入多条数据
table_name = "students"
datas = [{
  "id" : 1,
  "name" : "Lucy",
  "age" : 18,
  "grade" : "72"
},{
  "id" : 2,
  "name" : "Jack",
  "age" : 19,
  "grade" : "84"
},{
  "id" : 3,
  "name" : "Mike",
  "age" : 20,
  "grade" : "92"
}]

for data in datas:
    keys = ','.join(data.keys())
    values = ','.join(['%s'] * len(data))
    sql_insert_data = f"INSERT INTO {table_name} ({keys}) VALUES ({values})"
    values = list(data.values())
    mycursor.execute(sql_insert_data, values)

# 提交事务
mydb.commit()

# 关闭游标和连接
mycursor.close()
mydb.close()

以上就是实现保存dict字典类型数据到Mysql并自动创建表与列的攻略。