我正在尝试编写一个生成器函数,该函数从数据库中获取行并一次返回一行。但是,我不确定下面标记为 ** 的清理代码是否按照我的想法执行。如果没有,将清理代码放入生成器本身并在最后一个yield语句之后执行的最佳方法是什么?我查看了捕获 StopIteration 但这似乎是由调用者完成的,而不是在生成器内完成的。
def MYSQLSelectGenerator(stmt):
...
try:
myDB = MySQLdb.connect(host=..., port=..., user=..., passwd=..., db=...)
dbc=myDB.cursor()
dbc.execute(stmt)
d = "asdf"
while d is not None:
d = dbc.fetchone() #can also use fetchmany() to be more efficient
yield d
dbc.close() #** DOES THIS WORK AS I INTEND, MEANING AS SOON AS d = "None"
except MySQLdb.Error, msg:
print("MYSQL ERROR!")
print msg
Run Code Online (Sandbox Code Playgroud) 在查看 Stack Exchange 提供的一些 websocket 方法时,我想将一些数据点保存到 MySQL 数据库中。但是,当我尝试运行命令时executemany,出现以下错误:
_mysql_exceptions.OperationalError: (1241, 'Operand should contain 1 column(s)')
在环顾四周时,我发现了许多此错误的例子,但他们已经处理了删除SELECT语句中的括号的问题。我没有使用SELECT. 我正在尝试INSERT。
我的代码的一个简短的包含示例如下所示:
import MySQLdb as mdb
db = mdb.connect(host='localhost',user='myuser',db='qs',passwd='mypass',use_unicode=True,charset='utf8')
cur = db.cursor()
db_qry = """INSERT IGNORE INTO questions (id, site_base, title, body_sum, tags, last_act_dt, url, owner_url, owner, api_site) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
parms = [(u'mathematica.stackexchange.com',
43248,
u'How to plot “Normalized distance” in this problem',
u"Problem: there are two particles whose equationsof motion both satisfy -n Abs[x[t]]^n/x[t] == x''[t]. …Run Code Online (Sandbox Code Playgroud) 我想编写一个生成器函数,该函数将在内存有限的系统上运行,该系统使用 PyMySql(或 MySQLDb)一次返回一个选择查询的结果。以下作品:
#execute a select query and return results as a generator
def SQLSelectGenerator(self,stmt):
#error handling code removed
cur.execute(stmt)
row = ""
while row is not None:
row = self.cur.fetchone()
yield row
Run Code Online (Sandbox Code Playgroud)
然而,以下内容似乎也有效,但它是否正在执行 fetchall() 是神秘的。我在 Python DB API 中找不到当您将游标对象作为列表进行迭代时到底会发生什么:
#execute a select query and return results as a generator
def SQLSelectGenerator(self,stmt):
#error handling code removed
cur.execute(stmt)
for row in self.cur:
yield row
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,以下内容都会成功打印所有行
stmt = "select * from ..."
for l in SQLSelectGenerator(stmt):
print(l)
Run Code Online (Sandbox Code Playgroud)
所以我想知道第二种实现是更好还是更差,以及它是调用 fetchall 还是用 fetchone 做一些棘手的事情。Fetchall …
我正在使用 python-mysql(MySQLdb) 来查询 Mysql 服务器。游标模块有两种:一种是客户端游标,如:
cursor = db.cursor(MySQLdb.cursors.DictCursor)
Run Code Online (Sandbox Code Playgroud)
另一种是服务器端游标,如:
cursor = db.cursor(MySQLdb.cursors.SSDictCursor)
Run Code Online (Sandbox Code Playgroud)
文档说服务器端游标意味着Mysql会在mysql服务器端缓存一些结果,然后将它们发送到客户端。我对此很困惑,比方说,如果我想杀死一台 mysql 服务器,我可以使用多个服务器端游标,然后 mysql 就会因为内存耗尽而死掉。此外,服务器大小光标有任何意义吗?默认情况下,Mysql 机制是当 mysql 检索到一条记录时,它会立即将其发送给客户端。缓存结果然后将其发送出去是否有意义?
我真的不知道应该使用哪个游标,客户端游标还是服务器端游标?
我正在尝试使用 python 访问数据库,但它不起作用。当我访问远程数据库时,一切都很好。但本地存在某种问题。我在这里做什么?我尝试过在 intener 上发现的一些东西确实授予访问权限,但它们不起作用
使用的代码:
已收到消息
谢谢您的帮助
我的 python 代码有问题,我想将其用于 REST API 服务器。
当前的问题是,当我知道该值存在时,我的数据库查询返回 null
具体路径的代码:
@app.route('/data/active_predicted/<int:ticketId>', methods=['GET'])
def search_db_tickId_act(ticketId):
cursor = db.cursor()
db_query = cursor.execute("select * from active_predicted where ticketId=" + str(ticketId))
json_output = json.dumps(dict(cursor.fetchall()))
cursor.close()
if not cursor.fetchall():
return "Nothing found \n SQL Query: " + "select * from active_predicted where ticketId=" + str(ticketId)
else:
return str(cursor.fetchall())
Run Code Online (Sandbox Code Playgroud)
当我访问此 URL 时,我会返回以下内容:
没有找到 SQL 查询: select * from active_predicted where TicketId=1324
当我插入这个 SQL 查询时,我得到了我想要的结果,1 行 2 列,但程序似乎无法找到该行?
我需要捕获一个特定的OperationalError异常。异常文本使用错误代码 2006。该库在 处定义了错误代码MySQLdb.constants.CR.SERVER_GONE_ERROR = 2006。
如何从异常中获取错误代码?
当我检查MySQLdb._mysql_exceptions时,有一个OperationalError异常的定义,但它没有构造函数或如何访问异常错误代码的描述。
我有一个 python 代码,通过 MySQLdb 访问 mysql 来运行 select 语句。然后,我将cursor.fetchall()输出收集为数组,但问题是它L在每个输出的末尾打印一个,如下所示:
sql = "SELECT data1, data2 FROM table1, table2 ;"
cursor.execute(sql)
dataarray = cursor.fetchall()
print dataarray
>>> ((75379L, 45708L), ...)
Run Code Online (Sandbox Code Playgroud)
但在我的表格中,没有 L,只有数字。我怎样才能确保它只获取并打印没有 L 的数据?我宁愿避免[:-1]在字符串上使用,因为这样它会将我的None值更改为Non.
这是我的 Dockerfile:
\n\nFROM python:2.7\nRUN apt-get update && apt-get -y upgrade\n#RUN apt-get install -y python-pip python-dev libmysqlclient-dev\nRUN pip install --upgrade pip\nRUN pip install MySQL-python==1.2.5\nRun Code Online (Sandbox Code Playgroud)\n\n当我构建它时,我收到以下错误:
\n\nStep 4/4 : RUN pip install MySQL-python==1.2.5\n ---> Running in 60be606a8d3e\nDEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won\'t be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 …Run Code Online (Sandbox Code Playgroud) 如何使用 pip 在 Amazon Linux 2/Python 3.8 实例中安装 mysqlclient?
\n我正在将 Django 应用程序部署到 Elastic Bean Stalk。当部署过程正在运行时pip install -r requirements.txt,它会失败,并且我在 eb-engine.log 上收到此错误。
\xc3\x97 Getting requirements to build wheel did not run successfully.\n \xe2\x94\x82 exit code: 1\n \xe2\x95\xb0\xe2\x94\x80> [22 lines of output]\n Trying pkg-config --exists mysqlclient\n Command \'pkg-config --exists mysqlclient\' returned non-zero exit status 1.\n Trying pkg-config --exists mariadb\n Command \'pkg-config --exists mariadb\' returned non-zero exit status 1.\n Traceback (most recent call last):\n File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>\n …Run Code Online (Sandbox Code Playgroud) python amazon-ec2 mysql-python amazon-web-services amazon-elastic-beanstalk
mysql-python ×10
python ×8
mysql ×5
amazon-ec2 ×1
arrays ×1
docker ×1
executemany ×1
fetchall ×1
generator ×1
pip ×1
pymysql ×1
python-2.7 ×1