通常我使用 Pandas 来查看和处理数据,这是我所熟悉的。
如果我使用 psycopg2 模块从 postgres 数据库中提取数据,我会将 SQL 查询放在一个 python 文件中,但如果它是一个复杂的查询,它会在远离屏幕的一行上扩展。
有没有办法在python中使用换行符获取sql查询?即某种特殊字符包装器使python忽略空格?
这个
sql = SELECT devices.id, devices.names, devices.addresses, devices.charging, devices.covered, record_temperatures.time
FROM devices
WHERE devices.imei like '%0444258';
df = pd.read_sql_query(sql, con=conn)
Run Code Online (Sandbox Code Playgroud)
不是这个
sql = SELECT devices.id, devices.names, devices.addresses, devices.charging, devices.covered, record_temperatures.time FROM devices WHERE devices.imei like '%0444258';
df = pd.read_sql_query(sql, con=conn)
Run Code Online (Sandbox Code Playgroud) 首先,我创建了一个包含 5 列的表:
CREATE TABLE table1
(
a integer,
b character varying,
c character varying,
d numeric,
e numeric
)
Run Code Online (Sandbox Code Playgroud)
其次,我向表中添加 100k 行
https://gist.github.com/ericsalim/1d12628826195b52c5d282c2326f5e00
第三,我使用 Psycopg2 和 SQLAlchemy 选择所有行
Psycopg2 的结果
SQLAlchemy 的结果:
作为 Psycopg2 顶部的 ORM 层的 SQLAlchemy 怎么可能比 Psycopg2 本身更快?我的代码有问题吗?
所以我正在做一个项目来学习 SQL、Python 和一些服务器端的东西,经过多次搜索,我在这一点上很难过。我想创建两个相同的表,我有以下代码:
import psycopg2 as db
import json
with open('config.json', 'r') as f:
config = json.load(f)
conn = db.connect(user=config['dbuser'], database=config['dbname'], host=config['dbhost'], password=config['dbpass']);
cur = conn.cursor()
cur.execute("""CREATE TABLE IF NOT EXISTS A
(
city TEXT,
location POINT NOT NULL,
eta INTEGER,
time TIMESTAMP WITH TIME ZONE NOT NULL,
holiday BOOLEAN,
PRIMARY KEY (location, time)
);""")
Run Code Online (Sandbox Code Playgroud)
还有表B,格式相同,其中A和B是不同的服务。运行此程序时,我得到:
Traceback (most recent call last):
File "dbsetup.py", line 18, in <module>
);""")
psycopg2.ProgrammingError: data type point has no default operator class for access method …Run Code Online (Sandbox Code Playgroud) 将 Postgresql 9.5 与 psycopg2 一起使用。
使用“返回”,我可以检索我插入的单行的“id”。
sql = "insert into %s (%s) values (%s) returning id" % (table_name, columns, values_template)
values = tuple(row_dict[key] for key in keys)
cur.execute(sql, values)
id_new_row = cur.fetchone()[0]
Run Code Online (Sandbox Code Playgroud)
我还希望检索使用该executemany语句插入的多行中最后一行的 id 。
cur.executemany(insert_sql , data_dict)
#get id of the last row inserted
id_new_row = cur.fetchone()[0]
Run Code Online (Sandbox Code Playgroud)
但这会引发 DatabaseError,“没有要获取的结果”。
这是根本不可能做的事情,还是我没有正确地要求结果?
我对 python 很陌生,这是我的第一门编程语言。这是我第一次尝试使用 SQL 和 psycopg2。非常感谢任何“愚蠢”的建议!
我不确定问题是什么。我的研究告诉我,我提供的参数太少或太多,cursor.execute(INSERT...但我尝试了许多不同的计数,但似乎无法正常工作。从我的角度来看,它cursor.execute(CREATE...创建了一个有 6 列的表,我将 6 个参数传递给它。
from lxml import html # Used to parse XML
import requests #used to service API request
itemtypeid1 = 34
itemtypeid2 = 35
regionid = 10000002
webpage = requests.get('http://api.eve-central.com/api/marketstat?typeid=%i&typeid=%i®ionlimit=%i' % (
itemtypeid1, itemtypeid2, regionid))
if webpage.status_code == 200:
data = html.fromstring(webpage.content)
for item in data.iter('type'):
buy_dict = {node.tag: node.text for node in item.xpath("buy/*")}
sell_dict = {node.tag: node.text for node in item.xpath("sell/*")}
#Variables for output
itemid = …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用此psycopg2使用 cursor.mogrify 将大量行插入 postgres :insert multiple rows with a query
data 是一个元组列表,其中每个元组是需要插入的一行。
cursor = conn.cursor()
args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)
cursor.execute(
"insert into table1 (n, p, r, c, date, p1, a, id) values " + args_str)`
Run Code Online (Sandbox Code Playgroud)
但得到错误:
TypeError: sequence item 0: expected str instance, bytes found
Run Code Online (Sandbox Code Playgroud)
在线:
args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)
Run Code Online (Sandbox Code Playgroud)
如果我尝试更改为b''.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data ),然后执行查询给出插入字节的错误....
难道我做错了什么 ?
我正在尝试使用 psycopg2 批量插入 postgres 数据库。我正在使用 %s 和一个元组列表,但它失败并出现以下错误:
File ".../python3.6/site-packages/psycopg2/extras.py", line 1183, in execute_batch
sqls = [cur.mogrify(sql, args) for args in page]
File ".../python3.6/site-packages/psycopg2/extras.py", line 1183, in <listcomp>
sqls = [cur.mogrify(sql, args) for args in page]
TypeError: not all arguments converted during string formatting
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import psycopg2
import psycopg2.extras
conn = psycopg2.connect(
database='mydb',
user='name',
password='pass')
cur = conn.cursor()
query = "INSERT INTO my_table (tweet_id, user_id, time, text,
reply_to_user_id, reply_to_tweet_id, reply_to_handle, is_retweet,
is_quote, quote_usr_id, quote_usr_handle, quote_id, quote_text,
retweet_usr_id, retweet_usr_handle, retweet_id, longitude, latitude, …Run Code Online (Sandbox Code Playgroud) 我为我的项目设置了 virtualenv 以及何时我想运行
pip 安装 psycopg2
我在下面收到错误
ERROR: Complete output from command python setup.py egg_info:
ERROR: running egg_info
creating pip-egg-info/psycopg2.egg-info
writing pip-egg-info/psycopg2.egg-info/PKG-INFO
writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt
writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt
writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt'
Error: pg_config executable not found.
pg_config is required to build psycopg2 from the source. Please add the directory
containing pg_config to the $PATH or specify the full executable path with the
option:
python setup.py build_ext --pg-config /path/to/pg_config build ...
or with the pg_config option in …Run Code Online (Sandbox Code Playgroud) 有什么魔术pipenv可以安装psycopg2吗?
我的Pipfile看起来像这样:
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
django = "==2.1.3"
psycopg2 = "*"
[dev-packages]
[requires]
python_version = "3.6"
Run Code Online (Sandbox Code Playgroud)
我已经尝试添加和删除 pyscopg2-binary 的安装,但没有任何区别。我在运行 OSX 10.14.4 的 Mac 上。
这是我运行后得到的输出pipenv install:
An error occurred while installing psycopg2==2.8.3 --hash=sha256:128d0fa910ada0157bba1cb74a9c5f92bb8a1dca77cf91a31eb274d1f889e001 --hash=sha256:227fd46cf9b7255f07687e5bde454d7d67ae39ca77e170097cdef8ebfc30c323 --hash=sha256:2315e7f104681d498ccf6fd70b0dba5bce65d60ac92171492bfe228e21dcc242 --hash=sha256:4b5417dcd2999db0f5a891d54717cfaee33acc64f4772c4bc574d4ff95ed9d80 --hash=sha256:640113ddc943522aaf71294e3f2d24013b0edd659b7820621492c9ebd3a2fb0b --hash=sha256:897a6e838319b4bf648a574afb6cabcb17d0488f8c7195100d48d872419f4457 --hash=sha256:8dceca81409898c870e011c71179454962dec152a1a6b86a347f4be74b16d864 --hash=sha256:b1b8e41da09a0c3ef0b3d4bb72da0dde2abebe583c1e8462973233fd5ad0235f --hash=sha256:cb407fccc12fc29dc331f2b934913405fa49b9b75af4f3a72d0f50f57ad2ca23 --hash=sha256:d3a27550a8185e53b244ad7e79e307594b92fede8617d80200a8cce1fba2c60f --hash=sha256:f0e6b697a975d9d3ccd04135316c947dd82d841067c7800ccf622a8717e98df1! Will try again.
???????????????????????????????? 7/7 — 00:00:45
Installing initially failed dependencies…
[pipenv.exceptions.InstallError]: File "/usr/local/Cellar/pipenv/2018.11.26_2/libexec/lib/python3.7/site-packages/pipenv/core.py", line 1874, in do_install
[pipenv.exceptions.InstallError]: keep_outdated=keep_outdated
[pipenv.exceptions.InstallError]: …Run Code Online (Sandbox Code Playgroud) 我收到这条消息:
Collecting psycopg2
Using cached https://files.pythonhosted.org/packages/84/d7/6a93c99b5ba4d4d22daa3928b983cec66df4536ca50b22ce5dcac65e4e71/psycopg2-2.8.4.tar.gz
Building wheels for collected packages: psycopg2
Building wheel for psycopg2 (setup.py) ... error
ERROR: Command errored out with exit status 1:
command: /Users/mohsen/.virtualenvs/jalas-env/bin/python3.7 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/vh/0_hbs48171574k5y9pb97st80000gn/T/pip-install-y72dxnyb/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/vh/0_hbs48171574k5y9pb97st80000gn/T/pip-install-y72dxnyb/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/vh/0_hbs48171574k5y9pb97st80000gn/T/pip-wheel-51dm_zyp --python-tag cp37
cwd: /private/var/folders/vh/0_hbs48171574k5y9pb97st80000gn/T/pip-install-y72dxnyb/psycopg2/
Complete output (144 lines):
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.15-x86_64-3.7
creating build/lib.macosx-10.15-x86_64-3.7/psycopg2
copying lib/_json.py -> build/lib.macosx-10.15-x86_64-3.7/psycopg2
copying lib/extras.py -> build/lib.macosx-10.15-x86_64-3.7/psycopg2
copying lib/compat.py -> build/lib.macosx-10.15-x86_64-3.7/psycopg2
copying …Run Code Online (Sandbox Code Playgroud) psycopg2 ×10
postgresql ×9
python ×9
sql ×2
django ×1
pip ×1
pipenv ×1
python-3.x ×1
sqlalchemy ×1
virtualenv ×1