前体:
MySQL Table created via:
CREATE TABLE table(Id INT PRIMARY KEY NOT NULL, Param1 VARCHAR(50))
Run Code Online (Sandbox Code Playgroud)
功能:
.execute("INSERT INTO table VALUES(%d,%s)", (int(id), string)
Run Code Online (Sandbox Code Playgroud)
输出:
TypeError: %d format: a number is required, not a str
Run Code Online (Sandbox Code Playgroud)
我不确定这里发生了什么,为什么我无法执行命令.这是在Python中使用MySQLdb..execute是在游标对象上执行的.
编辑:
主题:Python MySQLdb问题(TypeError:%d格式:需要一个数字,而不是str) 表示必须对所有字段使用%s.为什么会这样?为什么这个命令有效?
.execute("INSERT INTO table VALUES(%s,%s)", (int(id), string)
Run Code Online (Sandbox Code Playgroud) 我正在使用MySQL的MySQLdb模块(用于Windows Python 2.7的v1.2.3预编译二进制文件)来读取和写入MySQL数据库的数据.一旦连接打开,我就可以使用该连接来观察在同一连接上对数据库所做的更改,但是看不到使用其他连接进行的更改,无论另一个连接是在Python中进行还是使用了更改MySQL命令行客户端.在我使用Python进行更新的情况下,请注意我在连接上运行commit()命令.
使用一个VARCHAR列将新记录插入测试表的程序示例:
import MySQLdb
conn = MySQLdb.connect("localhost", "test", "test", "test")
c = conn.cursor()
c.execute("INSERT INTO test VALUES(%s)", ("Test",))
conn.commit()
c.close()
conn.close()
Run Code Online (Sandbox Code Playgroud)
最终打印常量记录计数的程序示例(而不是打印最新的记录计数).我只能通过杀死和重新运行脚本或每次SELECT运行语句时打开一个新连接来更新计数.
import MySQLdb
conn = MySQLdb.connect("localhost", "test", "test", "test")
while True:
input = raw_input("Enter anything: ")
if input == "exit":
break
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM test")
res = c.fetchone()[0]
c.close()
print("Number of records: %d" % res)
Run Code Online (Sandbox Code Playgroud) 我正在使用MySQLdb包在python中执行mysql查询.代码看起来像这样:
c=db.cursor()
c.execute("""select * from table""")
output = []
for row in c:
output.append(row[4])
Run Code Online (Sandbox Code Playgroud)
其中row[4]包含我想要存储在output列表中的十进制值.
问题是我得到的每一个值都是这样的:列表中Decimal('XX.XX')我想要的output只是XX.XX. 在脚本的末尾,我的output列表如下所示:
[Decimal('10.02'), Decimal('20.24'), ...]
Run Code Online (Sandbox Code Playgroud)
但我需要它来包含数字,如下所示:
[10.02, 20.24, ...]
Run Code Online (Sandbox Code Playgroud)
我怎么做?
谢谢!
好的,我最近从Ubuntu 10.04升级到12.04
只是面临很多问题.我是一个新手,所以你可能需要更详细或一步一步地告诉我
我有一个完美的django项目,但现在它给了我这个错误:
File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 16, in <module>
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
Run Code Online (Sandbox Code Playgroud)
或者在python中:
>>> import MySQLdb
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-i686/egg/MySQLdb/__init__.py", line 19, in <module>
File "build/bdist.linux-i686/egg/_mysql.py", line 7, in <module>
File "build/bdist.linux-i686/egg/_mysql.py", line 6, in __bootstrap__
ImportError: libmysqlclient_r.so.16: cannot open shared object file: No such file or directory
Run Code Online (Sandbox Code Playgroud)
无论如何我认为我的MySQL-python存在一些问题,所以我尝试重新安装它. …
我已经通过xcode-select --install安装了工具,但在执行时仍然显示以下错误 pip install MySQL-python
Building wheels for collected packages: MySQL-python
Running setup.py bdist_wheel for MySQL-python ... error
Complete output from command /Users/vaibhavmule/Envs/switchidea/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/private/var/folders/p6/0v0bflxn3t399_qdpnm2z7hc0000gn/T/pip-install-SD9Cgh/MySQL-python/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/p6/0v0bflxn3t399_qdpnm2z7hc0000gn/T/pip-wheel-g6C50k --python-tag cp27:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.13-x86_64-2.7
copying _mysql_exceptions.py -> build/lib.macosx-10.13-x86_64-2.7
creating build/lib.macosx-10.13-x86_64-2.7/MySQLdb
copying MySQLdb/__init__.py -> build/lib.macosx-10.13-x86_64-2.7/MySQLdb
copying MySQLdb/converters.py -> build/lib.macosx-10.13-x86_64-2.7/MySQLdb
copying MySQLdb/connections.py -> build/lib.macosx-10.13-x86_64-2.7/MySQLdb
copying MySQLdb/cursors.py -> build/lib.macosx-10.13-x86_64-2.7/MySQLdb
copying MySQLdb/release.py -> build/lib.macosx-10.13-x86_64-2.7/MySQLdb
copying MySQLdb/times.py -> build/lib.macosx-10.13-x86_64-2.7/MySQLdb
creating build/lib.macosx-10.13-x86_64-2.7/MySQLdb/constants …Run Code Online (Sandbox Code Playgroud) 我正在使用 Debian/Ubuntu,并且尝试在我的 Python 虚拟环境中安装 Airflow 提供程序:
\n$ pip install apache-airflow-providers-mysql\n error: subprocess-exited-with-error\n\n \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> [24 lines of output]\n /bin/sh: 1: pkg-config: not found\n /bin/sh: 1: pkg-config: not found\n Trying pkg-config --exists mysqlclient\n Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127.\n Trying pkg-config --exists mariadb\n Command 'pkg-config --exists mariadb' returned non-zero exit status 127.\n Traceback (most recent call last):\n File "/home/user/airflow/airflow_env/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module>\n main()\n …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Python 2.7安装MySQLdb.我得到的错误看起来像这样:
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/opt/python2.7/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64
gcc -pthread -shared build/temp.linux-x86_64-2.7/_mysql.o -L/usr/lib64/mysql -L. -lmysqlclient_r -lz -lpthread -lcrypt -lnsl -lm -lpthread -lmygcc -lpython2.7 -o build/lib.linux-x86_64-2.7/_mysql.so
/usr/bin/ld: cannot find -lpython2.7
collect2: ld returned 1 exit status
error: command 'gcc' failed with exit status 1
Run Code Online (Sandbox Code Playgroud)
显然,它找不到Python 2.7.看着/usr/bin我看到:
python*
python2@
python2.4*
python2.7@
Run Code Online (Sandbox Code Playgroud)
什么是@符号是什么意思?任何人都可以建议补救错误?
我在创建数据库和表时遇到了麻烦.需要在Python脚本中创建数据库.
#connect method has 4 parameters:
#localhost (where mysql db is located),
#database user name,
#account password,
#database name
db1 = MS.connect(host="localhost",user="root",passwd="****",db="test")
Run Code Online (Sandbox Code Playgroud)
回报
_mysql_exceptions.OperationalError: (1049, "Unknown database 'test'")
Run Code Online (Sandbox Code Playgroud)
很明显,首先需要创建db1,但是如何?我在connect()语句之前尝试过CREATE但是出错了.
创建数据库后,如何创建表?谢谢,汤姆
这是语法,这至少是第一次使用.第二次自然返回db已经存在.现在来弄清楚如何正确使用drop命令.
db = MS.connect(host="localhost",user="root",passwd="****")
db1 = db.cursor()
db1.execute('CREATE DATABASE test1')
Run Code Online (Sandbox Code Playgroud)
所以第一次这很好用.第二次通过提供警告"db已存在".怎么处理这个?以下是我认为它应该如何工作,但事实并非如此.或者它应该是if语句,寻找它是否已经存在,不填充?
import warnings
warnings.filterwarnings("ignore", "test1")
Run Code Online (Sandbox Code Playgroud) 我们尝试将包含多个插入语句的SQL文件作为单个查询运行,但是rollback当任何语句包含错误时,它似乎都失败了.
MySQLd配置:
sql_mode = STRICT_ALL_TABLES
default-storage-engine = innodb
Run Code Online (Sandbox Code Playgroud)
Python代码:
from contextlib import closing
import MySQLdb
database_connection = MySQLdb.connect(host="127.0.0.1", user="root")
with closing(database_connection.cursor()) as cursor:
database_connection.begin()
cursor.execute('DROP DATABASE IF EXISTS db_name')
cursor.execute('CREATE DATABASE db_name')
cursor.execute('USE db_name')
cursor.execute('CREATE TABLE table_name(first_field INTEGER)')
with closing(database_connection.cursor()) as cursor:
try:
database_connection.begin()
cursor.execute('USE db_name')
cursor.execute('INSERT INTO table_name VALUES (1)')
cursor.execute('INSERT INTO table_name VALUES ("non-integer value")')
database_connection.commit()
except Exception as error:
print("Exception thrown: {0}".format(error))
database_connection.rollback()
print("Rolled back")
with closing(database_connection.cursor()) as cursor:
try:
database_connection.begin()
cursor.execute('USE db_name')
cursor.execute('INSERT INTO …Run Code Online (Sandbox Code Playgroud) 以下逻辑适用于mysqldb模块(请参阅python mysqldb一个连接的多个游标),但我在cursor2.execute(sql)上使用mysql.connector收到以下错误
"发现未读结果."
我意识到我可以使用连接来组合这两个简单的sql语句,并避免需要第二个游标,但我的真实世界的例子更复杂,需要第二个sql语句.
假设我需要执行2个单独的sql语句(1个用于循环,1个用于循环),如何使用mysql.connector模块完成?
import datetime
import mysql.connector
db = mysql.connector.connect(user='alan', password='please', host='machine1', database='mydb')
cursor1 = db.cursor()
cursor2 = db.cursor()
sql = """
SELECT userid,
username,
date
FROM user
WHERE date BETWEEN %s AND %s
"""
start_date = datetime.date(1999, 1, 1)
end_date = datetime.date(2014, 12, 31)
cursor1.execute(sql, (start_date, end_date))
for (userid, username, date) in cursor1:
sql = """
select count(*)
from request
where assigned = '%s'
""" % (userid)
cursor2.execute(sql)
requestcount = cursor2.fetchone()[0]
print userid, requestcount
cursor2.close() …Run Code Online (Sandbox Code Playgroud) mysql-python ×10
python ×8
mysql ×5
airflow ×1
cursor ×1
debian ×1
django ×1
linux ×1
python-3.x ×1
setuptools ×1
ubuntu ×1