我正在尝试使用 MySQLdb 模块删除数据库中的记录。在https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html 中,我发现multi=True在执行中执行多个查询但它产生错误。有人可以帮助我知道我缺少什么吗?
query = "DELETE FROM Service_Machine WHERE Id=(SELECT Id FROM Machines WHERE Id="+id+");" \
"DELETE FROM Machine_Usage WHERE Id=(SELECT Id FROM Machines WHERE Id="+id+");" \
"DELETE FROM Machines WHERE Id="+id+");
print(query)
self.cursor.execute(query, multi=True)
Run Code Online (Sandbox Code Playgroud) 我正在使用连接器/Python 将多行插入到 mysql 的临时表中。这些行都在一个列表列表中。我像这样执行插入:
cursor = connection.cursor();
batch = [[1, 'foo', 'bar'],[2, 'xyz', 'baz']]
cursor.executemany('INSERT INTO temp VALUES(?, ?, ?)', batch)
connection.commit()
Run Code Online (Sandbox Code Playgroud)
我注意到(当然还有更多的行)性能非常差。使用 SHOW PROCESSLIST,我注意到每个插入都是单独执行的。但是文档https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-executemany.html说这应该优化为 1 个插入。这是怎么回事?
执行以下代码时:
import mysql.connector
connection = mysql.connector.connect(...) # connection params here
cursor = connection.cursor()
cursor.execute('create table test_table(value blob)')
cursor.execute('insert into test_table values (_binary %s)', (np.random.sample(10000).astype('float').tobytes(),))
cursor.execute('select * from test_table')
cursor.fetchall()
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 1 中的字节 0xf7:起始字节无效
(...然后是我认为在这里没有用的堆栈跟踪)
似乎 mysql 连接器将我的 blob 转换为字符串(并且没有这样做)。如何在不进行任何转换的情况下将这些数据作为字节获取?
我是 Python 单元测试的新手,我不确定如何创建此函数的单元测试以返回连接?
def connection(self):
connection = mysql.connector.connect(host='localhost',
database='test',
user='user',
password='password',
auth_plugin='mysql_native_password')
return connection
Run Code Online (Sandbox Code Playgroud) python python-unittest mysql-connector-python python-unittest.mock
我有这个问题:我正在编写一些Python脚本,而到目前为止,我在整个脚本中使用单个MySQLConnector连接没有任何问题(仅在脚本末尾关闭它),最近我有一些问题。
如果我在脚本开头创建一个连接,类似于(我知道,忽略安全问题):
db_conn = mysql.connector.connect(user='root', password='myPassword', host='127.0.0.1', database='my_db', autocommit=True)
Run Code Online (Sandbox Code Playgroud)
然后总是像这样使用它:
db_conn.cursor(buffered=True).execute(...)
Run Code Online (Sandbox Code Playgroud)
或 fetch 等方法,我会收到如下错误:
Failed executing the SQL query: MySQL Connection not available.
Run Code Online (Sandbox Code Playgroud)
或者
Failed executing the SQL query: No result set to fetch from.
Run Code Online (Sandbox Code Playgroud)
或者
OperationalError: (2013, 'Lost connection to MySQL server during query')
Run Code Online (Sandbox Code Playgroud)
代码是正确的,我只是不明白为什么会发生这种情况。也许是因为我在异步中多次同时运行同一个函数(尝试了 2 次),所以也许对游标的并发访问会导致这种情况?
我发现有人每次都使用不同的数据库连接来修复它(此处)。
我尝试为数据库的每个查询创建一个新连接,现在根本没有错误。它工作得很好,但似乎有点矫枉过正。想象一下调用异步函数 10 或 100 次...将会创建大量数据库连接。会引起问题吗?内存会耗尽吗?而且,我想它会放缓。
有没有办法通过为所有查询保持相同的连接来解决这个问题?为什么会发生这种情况?
python mysql mysql-python mysql-connector-python database-cursor
我是 django 新手,正在尝试创建一个主页。但我已经遇到了数据库设置的问题。当我跑步时
python manage.py migrate
Run Code Online (Sandbox Code Playgroud)
我收到这个错误
(env) paul@Kreker-Server:~/public_html/p_kreker$ python manage.py migrate
Operations to perform:
Apply all migrations: auth, sessions, contenttypes, admin
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying sessions.0001_initial... OK
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/home/paul/public_html/p_kreker/env/lib/python3.4/site-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options) …Run Code Online (Sandbox Code Playgroud) 有人可以帮我弄清楚以下代码有什么问题.这是一个Python应用程序试图使用Connector/Python从mysql数据库中进行选择
number = '+12345678901'
cursor.execute('SELECT * FROM channel WHERE phone_number = %s', (number))
Run Code Online (Sandbox Code Playgroud)
它产生以下错误:
1064(42000):您的SQL语法有错误; 检查与MySQL服务器版本对应的手册,以便在第1行的'%s'附近使用正确的语法
当我检查mysql日志时,我看到以下内容:
SELECT*FROM channel WHERE phone_number =%s
这意味着它不能代替电话号码.
我必须从数据库中检索数据。现在我正在使用以下代码:
import mysql.connector
connection = mysql.connector.connect(user, password, host, database)
cursor = connection.cursor()
cursor.execute(*Query*)
data = cursor.fetchall()
name = data[0][0]
surname = data[0][1]
Run Code Online (Sandbox Code Playgroud)
我需要按字段名称而不是原始索引访问数据。例如类似的东西
name = data[0]['name']
surname = data[0]['surname']
Run Code Online (Sandbox Code Playgroud)
谢谢
我有以下格式的查询,
DROP TABLE X;
CREATE TEMPORARY TABLE IF NOT EXISTS X (SELECT * FROM TABLE);
SELECT A,B,C FROM X;
但是,如果我使用 mysql 连接器在 Python 中运行它。我收到以下消息,'No result set to fetch from'。我的理解是它只执行第一个DROP TABLE X;并返回。还有其他方法可以实现这一目标吗?我也尝试过使用multi=True,但也没有用。提前致谢
python mysql-connect mysql-connector mysql-python mysql-connector-python
我正在尝试遍历数组并将每个元素插入表中。据我所知,我的语法是正确的,我直接从Microsoft Azure的文档中获取了此代码。
try:
conn = mysql.connector.connect(**config)
print("Connection established")
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with the user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cursor = conn.cursor()
data = ['1','2','3','4','5']
for x in data:
cursor.execute("INSERT INTO test (serial) VALUES (%s)",(x))
print("Inserted",cursor.rowcount,"row(s) of data.")
conn.commit()
cursor.close()
conn.close()
print("Done.")
Run Code Online (Sandbox Code Playgroud)
当我运行时,它到达cursor.execute(...)然后失败。这是堆栈跟踪。
追溯(最近一次通话最后一次):在cursor.execute中的文件“ test.py”,第29行(“插入测试(串行)值(%s)”,(“测试”)))文件“ C:\ Users \ AlexJ \ AppData \ Local \ Programs \ Python \ Python37 …