-
安装Python
如果您还没有安装Python,请从Python官方网站(https://www.python.org/downloads/)下载并安装最新版本的Python。 -
安装必要的库(如果未安装)
在命令行或终端中运行以下命令,安装pymysql库:
pip install pymysql
3,编辑脚本
import pymysql
import argparse
def generate_insert_statements(table_name, columns, rows):
insert_statements = []
for row in rows:
values = ', '.join("'" + str(value).replace("'", "''") + "'" if value is not None else 'NULL' for value in row)
insert_statement = "INSERT INTO `{}` ({}) VALUES ({});".format(
table_name, ', '.join(columns), values)
insert_statements.append(insert_statement)
return insert_statements
def main(order_no, output_file):
# 创建数据库连接
connection = pymysql.connect(
host='localhost',
user='root',
password='123456',
database='test',
port=3306 # 在这里指定端口号
)
try:
with connection.cursor() as cursor:
table_queries = [
('tablename1(表名称)', "SELECT column1, column2, column3 FROM `tablename1` WHERE `order_no`='{}';".format(order_no)),
('tablename2(表名称)', "SELECT * FROM `tablename2` WHERE order_no='{}';".format(order_no)),
]
all_insert_statements = []
for table_name, query in table_queries:
cursor.execute(query)
columns = [desc[0] for desc in cursor.description]
rows = cursor.fetchall()
insert_statements = generate_insert_statements(table_name, columns, rows)
all_insert_statements.extend(insert_statements)
with open(output_file, 'w', encoding='utf-8') as f:
for statement in all_insert_statements:
f.write(statement + '\n')
finally:
connection.close()
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Generate SQL insert statements for a given order_no and export to a file.")
parser.add_argument("order_no", help="The order number to generate insert statements for.")
parser.add_argument("output_file", help="The file to write the SQL insert statements to.")
args = parser.parse_args()
main(args.order_no, args.output_file)
4,到该命令文件目录下执行命令:
python export_data.py 123456789 aaa.sql