Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取sql查询_Python_Mysql Python - Fatal编程技术网

在python中读取sql查询

在python中读取sql查询,python,mysql-python,Python,Mysql Python,我有点迷失在我想做的事情中。学习如何在Python中运行sql 我有一个Python sqlite中的db,有三个表1、2、3 然后,我在.sql文件中编写了一系列查询 我创建了一个循环,但是我缺少读取和执行sql文件的步骤 # For each of the 3 tables, query the database and print the contents for table in ['1', '2', '3']: # Plug in the name of the table into

我有点迷失在我想做的事情中。学习如何在Python中运行sql

我有一个Python sqlite中的db,有三个表1、2、3

然后,我在.sql文件中编写了一系列查询

我创建了一个循环,但是我缺少读取和执行sql文件的步骤

# For each of the 3 tables, query the database and print the contents
for table in ['1', '2', '3']:

# Plug in the name of the table into SELECT * query
result = c.execute("SELECT * FROM %s;" % table);

# Get all rows.
rows = result.fetchall();

# \n represents an end-of-line
print "\n--- TABLE ", table, "\n"

我的sql查询写在一个名为querys.sql的单独的.sql文件中。我应该把它放在循环中的什么地方?

发布sql查询以帮助您更好地完成任务。但是循环很容易做到这一点-

#before the loop create mysql client & 
#create cursor to mysql server

for sql_query_template in open(sql_queries_file,'r'):
    result = c.execute(sql_query_template % table);
    rows   = result.fetchall();
    print 'Rows Fetched: %d' % len(rows)

我希望你明白了……

我明白了。我复制了上述内容,但在NameError:name“table”中的第2行出现了错误“Traceback(最近一次调用):File”,未定义“@mylesg这段代码应添加到您的代码中,变量如文件名集,然后在
for table
循环中缩进,以及其他命令,因此,
由循环定义。@mylesg您需要自定义此代码以适合您的循环。我不知道什么是
表格。最后,
table
是一个变量,它具有要对其执行查询的表名。