首页 > 解决方案 > 使用 Python/SQL (pymysql) 将列/数据拆分为多个不同的表

问题描述

我正在尝试通过拆分我已使用 pymysql python 脚本上传到 MySQL phpmyadmin 数据库的现有表来规范化表。到目前为止,我已经能够将数据上传到表(tableName)中,但现在我需要将表(tableName)分解为多个表(例如,取 2 列并为其创建一个单独的表,其中的值来自这些列的原始表)。我怎样才能做到这一点?有人告诉我选择进入查询会起作用,但我似乎无法弄清楚。

这是我的代码:

conn = pymysql.connect(host = 'xxxx', user = 'root', password = '', autocommit = True, port = xxxx)
# reading in the dataset that needs to be uploaded to the database
csv = csv.reader(open('data.csv'))
# using the cursor to write queries and execute them
try:
    with conn.cursor() as cursor:
        # query for creating the database Assignment
        SQLCreateDatabase = "CREATE DATABASE IF NOT EXISTS Assignment"
    
        cursor.execute(SQLCreateDatabase)
        # selecting the database
        conn.select_db('Assignment')
        # creating table for tableName in the Assignment database
        SQLCreateTable = "CREATE TABLE IF NOT EXISTS tableName(time INT, 
DISCHARGE_PRESSURE DEC, INTAKE_PRESSURE DEC, INTAKE_TEMPERATURE DEC, MOTOR_TEMP DEC)"
    
        cursor.execute(SQLCreateTable)
    
        # inserting data from tableName dataset into the tableName table in sql
        for row in csv:
            cursor.execute('INSERT INTO tableName VALUES (%s, %s, %s, %s, %s)', row)

# closing the connection            
finally:
    conn.close()

标签: pythonmysqldatabasephpmyadminpymysql

解决方案


推荐阅读