我有以下数据:
table_name=xyz
column_names=['c1', 'c2', 'c3', 'c4']
column_datatypes=['VARCHAR(40)', 'BIGINT(40)', 'BIGINT(20)', 'VARCHAR(10)'] 我正在从文件.i.e中读取上面列表的长度可以vary.So,我希望创建一个动态的'CREATE‘MySQL查询,例如:
CREATE TABLE xyz(c1 VARCHAR(40),c2 BIGINT(40),c3 BIGINT(20),c4 VARCHAR(10));如何伪造上面这样的字符串查询(可能使用string.format())?
另外,请把问题提出来(如果值得的话),因为我即将被阻止去问更多的问题,因为我以前的问题没有得到任何表决。
发布于 2018-07-06 07:01:57
这就是你要的!
import MySQLdb as mdb
table_name='xyz'
column_names=['c1', 'c2', 'c3', 'c4']
column_datatypes=['VARCHAR(40)', 'BIGINT(40)', 'BIGINT(20)', 'VARCHAR(10)']
db=mdb.connect(host='localhost',user='root',passwd='*****',db='test',port=3306)
cursor=db.cursor()
create_stement='create table '+table_name + '('
i=0
while i< len(column_names)-1 :
create_stement =create_stement +column_names[i] +' '+column_datatypes[i]+' ,'
i=i+1
create_stement =create_stement +column_names[i] +' '+column_datatypes[i]+' )'
print(create_stement)
cursor.execute(create_stement)
print('Done')https://stackoverflow.com/questions/51203273
复制相似问题