python - MySQL 和 Python-插入

标签 python mysql sql database

我正在尝试将一些值插入到我的表中。代码是:

import MySQLdb

db=MySQLdb.connect(host="localhost",user="user_name", passwd="",db="name_of_db", port=3306)
cursor=db.cursor()
readcount=52
sql="Insert into pressure_image(idItem, pressure_val, image_loc, array_time, Time_Stamp) values ('%d', 260, 'a.jpg', 'aray', 14-11-2000)"
try:
    cursor.execute(sql, (readcount))
    db.commit()
except:
    print "No value inserted"
    db.rollback()

问题是当我尝试插入命令时,例如:

sql="插入压力_image(idItem、压力_val、image_loc、array_time、Time_Stamp)值(30, 260, 'a.jpg', 'aray', 14-11-2000)"这些值已正确插入表中,但是当我尝试代码中给出的命令时,没有插入任何值。因此本质上,常量有效,但变量则无效。

如何将变量插入表中?

最佳答案

尝试添加逗号:

cursor.execute(sql, (readcount,))

这里(readcount) == readcount,但是(readcount,)是一个包含 readcount的元组。

同时将查询中的 %d 替换为 %s。 正如 documentation 中所述

execute(self, query, args=None)

query - string, query to execute on server

args - optional sequence or mapping, parameters to use with query.

Note: If args is a sequence, then %s must be used as the parameter placeholder in the query. If a mapping is used, %(key)s must be used as the placeholder.

因此,MySQLdb 强制我们对 args 参数(可以是任何可迭代类型)和 %s 使用序列。使用 %s 格式说明符是因为在格式化查询之前,args 中的值会被转义并转换为字符串。

关于python - MySQL 和 Python-插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23082932/

相关文章:

Python flask - "Check if the username exists in the MySQL database"

mysql - ib_logfile 在哪里?

python - 拆分包含多个字典的列表

MYSQL 'select count(distinct col)' 结果错误?

python - 使用 pyodbc 将 SQL Server 中的数据读取到 pandas

java - 使用 getJdbcTemplate.query(sql,new Object[],rowmapper)) 时如何使用 union 运算符设置 sql 查询的参数?

sql - 为什么单独实例化的 Func<T,bool> 谓词不使用 Entity Framework 转换为 SQL?

python - 将 elif 语句添加到生成器表示法中

python - 安排 SQLAlchemy 清除表中的所有行

python random.randint 与 random.choice : different outcomes usingsame values