我是python3的新手。我的作业是创建一个包含10个表的Sqlite数据库,每个表包含50列,每列包含1000行,数据是使用Python随机生成的。我差不多做完了
我的代码:
import sqlite3
conn = sqlite3.connect('testmydb.db')
cur = conn.cursor()
for table_number in range(1,11):
cur.execute('''CREATE TABLE table''' + str(table_number) + '''(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT)''')
listOfColumns = ("column0",)
for column_number in range(1,49):
newColumn = ("column" + str(column_number),)
listOfColumns = listOfColumns + newColumn
for column_number in listOfColumns:
cur.execute('''ALTER TABLE table''' + str(table_number) + ''' ADD COLUMN %s TEXT''' % column_number)
conn.commit()
cur.close()
conn.close()
现在我想在1列中插入1000行,但是当我想创建更多的for
循环时,我感到困惑。有人能推荐我吗
以下内容应满足您的要求(参见备注)
这将产生如下输出(第一行是第一条INSERT语句/SQL):-
第一行第二行
if table_number == 1: print(insertsql)
正在打印INSERT语句以显示其外观。它只是包含在其中,没有必要。但是,知道它是什么样子来解释这个问题是有用的?占位符和绑定值
所以INSERT语句是沿着
注释中的第一个null允许SQLite为id列生成唯一值
每个人?是占位符,将被绑定值替换。这种技术可以防止SQL注入
bindMarkers只是一个由1生成的字符串?因此它是一个49英寸的字符串(比键入
VALUES(null,?,?,?,?,? .....)
更容易,而且如果列号要更改,也更灵活/适应性更强)您可以看到
listOfRandomValues =[random.randint(1, 999999999999) for i in range(49)]
行创建了一个包含49个随机值的列表,每个随机值将用于替换单个值?(第一个值替换第一个?,第二个值替换第二个?,依此类推)这被认为是比按照
语句本身较短(即1?而不是12位数字),因此不太可能引起限制问题
相关问题 更多 >
编程相关推荐