使用Python将单个数据插入MySQL表的步骤如下:
mysql-connector-python
)。import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
except Error as e:
print("连接MySQL数据库失败:", e)
请将localhost
替换为MySQL服务器的主机名,your_database
替换为要连接的数据库名称,your_username
和your_password
替换为相应的用户名和密码。
cursor = connection.cursor()
insert_query = "INSERT INTO your_table (column1, column2, ...) VALUES (%s, %s, ...)"
data = ('value1', 'value2', ...)
请将your_table
替换为要插入数据的表名,column1, column2, ...
替换为要插入数据的列名,value1, value2, ...
替换为要插入的实际值。
cursor.execute(insert_query, data)
connection.commit()
cursor.close()
connection.close()
完整的示例代码如下:
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
cursor = connection.cursor()
insert_query = "INSERT INTO your_table (column1, column2, ...) VALUES (%s, %s, ...)"
data = ('value1', 'value2', ...)
cursor.execute(insert_query, data)
connection.commit()
except Error as e:
print("插入数据失败:", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
请将示例代码中的your_database
、your_username
、your_password
、your_table
、column1, column2, ...
、value1, value2, ...
替换为相应的值。
这是一个基本的示例,你可以根据实际情况进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云