python+mysql中数据库表名为变量处理方式
#!/usr/bin/python3
import pymysql ,re,json
host="localhost"
user="root"
password="root"
DB="TC_alg_test"
port=3306
def Create_db(table_name):
# 打开数据库连接
db = pymysql.connect(host, user, password, DB)
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS %s"%(table_name)) #表名为变量
# 使用预处理语句创建表
sql = """CREATE TABLE %s(
TestID INT,
TestTime CHAR(100),
Template CHAR(100),
TestChart CHAR(100),
EstimatesRanged CHAR(20),
TestType CHAR(20),
TestValue float (6,3) NOT NULL,
Timeconsuming float(6,3) NOT NULL,
Result CHAR(20),
Color CHAR(20),
TemplatePath CHAR(200),
TestChartPath CHAR(200))"""%(table_name)#表名为变量
cursor.execute(sql)
# 关闭数据库连接
db.close()
def Insert_data(dic,table_name):
# 打开数据库连接
db = pymysql.connect(host, user, password, DB)
# 使用cursor()方法获取操作游标
cursor = db.cursor()
path=({"wide":dic["TemplatePath"],"tele":dic["TestChartPath"]})
TestID=dic["TestID"]
TestTime=dic["Time"]
Template=dic["Template"]
TestChart=dic["TestChart"]
EstimatesRanged=dic["EstimatesRanged"]
TestType=dic["TestType"]
TestValue=dic["TestValue"]
Timeconsuming=dic["Time-consuming"]
Result=dic["result"]
Color=dic["color"]
TemplatePath=dic["TemplatePath"]
TestChartPath=dic["TestChartPath"]
# SQL 插入语句
sql = "INSERT INTO %s (TestID, \
TestTime, Template, TestChart, EstimatesRanged,TestType,TestValue,Timeconsuming,Result,Color,TemplatePath,TestChartPath) \
VALUES (%s, '%s','%s', '%s','%s','%s',%s,%s,'%s','%s','%s','%s')" % \
(table_name,TestID, TestTime, Template,TestChart,EstimatesRanged,TestType,TestValue,Timeconsuming,Result,Color,TemplatePath,TestChartPath,)#表名为变量
try:
# 执行sql语句
cursor.execute(sql)
# 执行sql语句
db.commit()
#cursor.connection.commit() # 执行commit操作,插入语句才能生效
except:
# 发生错误时回滚
db.rollback()
#cursor.close()
# 关闭数据库连接
db.close()