我正在使用之前从另一个数据库中选择的~11.000.000行填充PostgreSQL表.我正在使用Python和psycopg2.整个过程大约需要1.5小时才能完成.但是,大约30分钟后我得到"连接意外关闭"异常.源代码如下所示:
incursor = indb.cursor()
incursor.execute("SELECT ...")
indb.commit() # (1) close transaction
outcursor = outdb.cursor()
rows = 0
for (col1, col2, col3) in incursor: # incursor contains ~11.000.000 rows
outcursor.execute("INSERT ...", (col1, col2, col3)) # This fails after ~30 minutes
row += 1
if row % 100 == 0: # (2) Write data every 100 rows
outcursor.close()
outdb.commit()
outcursor = outdb.cursor()
incursor.close()
outcursor.close()
outdb.commit()
Run Code Online (Sandbox Code Playgroud)
我插入(1)
并(2)
在第一次尝试失败后,假设打开的事务具有约30分钟的上限时间或者游标具有挂起插入的上限.似乎这些假设都不是真的,错误就在其他地方.
两个数据库都存储在VirtualBox机器上,我通过端口转发从主机连接.我在主机上运行程序.
这两个数据库仅用于测试目的,并且没有其他管理连接.也许我必须重写问题来解决这个问题,但我需要在其他地方非常耗时的插入(运行大约几天)所以我非常担心psycopg2
PostgreSQL中的一些隐藏时间限制.
当我通过 psql 客户端运行这个 SQL 查询时,它运行了几秒钟(~90 秒,这是正常的,因为它是一个巨大的表)然后它返回,然后我可以检查我的行是否已成功插入。
SELECT merge_data('898989', '111111111', '10000')
Run Code Online (Sandbox Code Playgroud)
它是一个运行 UPDATE 或 INSERT 的存储过程,该过程运行时没有错误,我在表中得到了我的条目。
当尝试从 python 程序执行相同操作时,查询需要 2 秒并且没有返回任何错误,我的表中什么也没有;有关信息,该语句在 postgresqk 支持上成功执行(我可以在 pgsql 日志中看到它),这是我的代码片段:
conn = psycopg2.connect("...")
cursor = conn.cursor()
try:
cursor.callproc("merge_data", ['898989', '111111111', '10000'])
except:
print "ERROR !"
cursor.close()
Run Code Online (Sandbox Code Playgroud) 所以我正在使用以下代码构建基于用户输入的查询:
if empty_indic_form.validate_on_submit():
query='select name, year, value, display_name from literal inner join ent on ent_id=ent.id where display_name in ('
for i in indic_form.indicators.data:
query=query+'\''+i+'\','
query=query[:-1]+') '
query=query+'and name in ('
for c in order_c:
query=query+c+','
query=query[:-1]+')'
data_return=db.engine.execute(query).fetchall()
Run Code Online (Sandbox Code Playgroud)
我已经确认查询看起来像它应该是什么,甚至有一个早期的会话,它返回一个像我期望的rowproxy对象列表.但是现在无论我做什么,我都会收到这个错误!
我已经将查询设置为模板中的变量,因此我可以将其打印出来,这是我得到的:
select name, year, value, display_name from literal inner join ent on ent_id=ent.id where display_name in ('Energy savings of primary energy (TJ)','Adolescent birth rate (women aged 15-19 years)','Net migration rate','Transmission and distribution losses (%)') and name in ('Burkina Faso', 'Ghana', 'Saudi Arabia', …
from django.db import connection
q = 'some value'
sql1 = 'SELECT * FROM table WHERE field LIKE %%%s%%' % q
sql2 = 'SELECT * FROM table WHERE field LIKE %%'+ q +'%%'
cursor = connection.cursor()
cursor.execute( sql1 ) #why exception: IndexError: tuple index out of range ?
cursor.execute( sql2 ) #works ok
Run Code Online (Sandbox Code Playgroud) 我是python的初学者.我们使用此代码来执行SQL命令.
cur.execute("INSERT INTO test (num, data) VALUES (%s, %s)", (100, "abcdef"))
Run Code Online (Sandbox Code Playgroud)
我想知道这是准备好的声明还是只是客户端引用?
我有一个非常简单的Python代码片段,用于运行Postgres查询,然后将结果发送到仪表板。我psycopg2
用来定期运行相同的查询。现在我们不用担心循环机制。
conn = psycopg2.connect(<connection info>)
while True:
# Run query and update dashboard
cur = conn.cursor()
cur.execute(q_tcc)
query_results = cur.fetchall()
update_dashboard(query_results)
time.sleep(5)
Run Code Online (Sandbox Code Playgroud)
供参考,实际查询是:
q_tcc = """SELECT client_addr, application_name, count(*) cnt FROM pg_stat_activity
GROUP BY client_addr, application_name ORDER BY cnt DESC;"""
Run Code Online (Sandbox Code Playgroud)
当我运行此命令时,即使应该更改它们,我也会得到相同的结果。如果我使用将该psycopg2.connect()
行移动到循环中conn.close()
,则一切正常。但是,根据connection和cursor文档,我应该能够一直使用相同的游标(并因此使用connection)。
这是否意味着Postgres会基于每个客户端连接来缓存我的查询?
我使用python中的postgresql更新了数据库表我的代码是
import psycopg2
connection=psycopg2.connect("dbname=homedb user=ria")
cursor=connection.cursor()
l_dict= {'licence_id':1}
cursor.execute("SELECT * FROM im_entry.usr_table")
rows=cursor.fetchall()
for row in rows:
i=i+1
p = findmax(row)
#print p
idn="id"
idn=idn+str(i)
cursor.execute("UPDATE im_entry.pr_table SET (selected_entry) = ('"+p+"') WHERE image_1d ='"+idn+"'")
print 'DATABASE TO PRINT'
cursor.execute("SELECT * FROM im_entry.pr_table")
rows=cursor.fetchall()
for row in rows:
print row
Run Code Online (Sandbox Code Playgroud)
我显示了更新的表格
但当我通过psql显示更新的表作为homedb =#SELECT*FROM im_entry.pr_table; 我显示了一个空表...有什么不对?请帮我
我无法使用pymc
沿psycopg2
.本教程中的以下简单片段:
import pymc as pm
with pm.Model() as model:
x = pm.Normal('x', mu=0., sd=1)
Run Code Online (Sandbox Code Playgroud)
导致以下错误:
例外:环境变量'DYLD_FALLBACK_LIBRARY_PATH'的值中不包含'/ Users/josh/anaconda/envs/py27/lib'路径.这将使Theano无法编译c代码.更新'DYLD_FALLBACK_LIBRARY_PATH'以包含所述值,这将修复此错误.
我能够通过添加以下内容来解决此问题:
export DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:/Users/josh/anaconda/envs/py27/lib
Run Code Online (Sandbox Code Playgroud)
到我的shell init文件.bashrc
.但是,这是我不理解的部分,那个换行psycopg2
:
---> 50 from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
51
52 from psycopg2._psycopg import Binary, Date, Time, Timestamp
ImportError: dlopen(/Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: @loader_path/../../../libpq.5.dylib
Referenced from: /Users/josh/anaconda/envs/py27/lib/python2.7/site-packages/psycopg2/_psycopg.so
Reason: image not found
Run Code Online (Sandbox Code Playgroud)
我怎么能psycopg2
和pymc
(在这里theano
)幸福地生活在一起?
这是在OS X上安装了Python 2.7.6,并使用conda创建了Python环境.
我正在尝试运行这样的代码:
query = "copy (select email from my_table) TO 'STDOUT' WITH (FORMAT csv, DELIMITER '|', QUOTE '^', HEADER FALSE)"
out_file = StringIO()
cursor.copy_expert(query, out_file, size=8192)
Run Code Online (Sandbox Code Playgroud)
但我收到此错误:
Traceback (most recent call last):
File "etl/scripts/scratch.py", line 32, in <module>
cursor.copy_expert(query, out_file, size=8192)
psycopg2.ProgrammingError: must be superuser to COPY to or from a file
HINT: Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
Run Code Online (Sandbox Code Playgroud)
我无权以超级用户身份运行它,而且由于我没有接触任何实际文件,因此似乎不需要这样做。
psycopg ×9
postgresql ×7
python ×6
psycopg2 ×3
database ×1
django ×1
flask ×1
macos ×1
pymc ×1
python-3.x ×1
sqlalchemy ×1
theano ×1