从pandas数据帧在MySQL数据库中创建新表的步骤如下:
import pandas as pd
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='your_database',
user='your_username',
password='your_password')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
请注意,将your_database
替换为您的数据库名称,your_username
替换为您的数据库用户名,your_password
替换为您的数据库密码。
df
的pandas数据帧,其中包含要插入到新表中的数据。try:
# 创建新表
cursor.execute("CREATE TABLE new_table (column1 datatype, column2 datatype, ...)")
print("New table created!")
# 将数据插入新表
for row in df.itertuples():
cursor.execute("INSERT INTO new_table (column1, column2, ...) VALUES (%s, %s, ...)", row[1:])
connection.commit()
print("Data inserted into new table!")
except Error as e:
print("Error while creating or inserting into MySQL table", e)
请注意,将new_table
替换为您想要创建的新表的名称,并根据您的数据帧调整列名和数据类型。
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
这样,您就可以从pandas数据帧中创建一个新表并将其插入到MySQL数据库中了。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云