免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3268 | 回复: 5
打印 上一主题 下一主题

python3 +MySQLdb 遇到的问题, [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-03-11 09:27 |只看该作者 |倒序浏览
B=2
count = cursor.execute('''select * from info where ID=%s''',(B,))


这样语句 没看出啥问题 总提示
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1")

为啥 ??

论坛徽章:
0
2 [报告]
发表于 2012-03-11 09:41 |只看该作者
没有这样的语法吧
  1. B=2
  2. sql="select * from info where ID=%s" % B
  3. cursor.execute(sql)
复制代码

论坛徽章:
0
3 [报告]
发表于 2012-03-11 09:54 |只看该作者
本帖最后由 aaa2520 于 2012-03-11 10:06 编辑

多谢,你的方法可以
难道是版本的问题?
我看的是这个
依葫芦画瓢。
http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects
The connect() method works nearly the same as with _mysql:

import MySQLdb
db=MySQLdb.connect(passwd="moonpie",db="thangs")
To perform a query, you first need a cursor, and then you can execute queries on it:

c=db.cursor()
max_price=5
c.execute("""SELECT spam, eggs, sausage FROM breakfast
          WHERE price < %s""", (max_price,))
In this example, max_price=5 Why, then, use %s in the string? Because MySQLdb will convert it to a SQL literal value, which is the string '5'. When it's finished, the query will actually say, "...WHERE price < 5".

Why the tuple? Because the DB API requires you to pass in any parameters as a sequence. Due to the design of the parser, (max_price) is interpreted as using algebraic grouping and simply as max_price and not a tuple. Adding a comma, i.e. (max_price,) forces it to make a tuple.

论坛徽章:
0
4 [报告]
发表于 2012-03-11 10:08 |只看该作者
如果我想一次插入数据怎么写?
c.execute("insert into info(title,Pnum,Pnei,Pdate,puser,pid) values(%s,%s,%s,%s,%s,%s)"  % (cs[0],cs[1],cs[2],cs[3],cs[4],cs[5]))

没理解 是个啥意思。

论坛徽章:
0
5 [报告]
发表于 2012-03-11 10:58 |只看该作者
本帖最后由 askandstudy 于 2012-03-11 10:59 编辑

你在3楼贴的原文确实是这么用的,我是用sqlite来试的,我的机器上没mysql,不好意思,等我装了mysql再试试那个用法看看

一次插入多行的例子可以这样啊,多行数据保存到一个元组列表变量中就行了。
cursor.executemany(
      """INSERT INTO breakfast (name, spam, eggs, sausage, price)
      VALUES (%s, %s, %s, %s, %s)""",
      [
      ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
      ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
      ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
      ] )

论坛徽章:
0
6 [报告]
发表于 2012-03-11 11:04 |只看该作者
本帖最后由 aaa2520 于 2012-03-11 11:09 编辑


sqlite 下我试验过
这样的语句 工作的挺好。
c.execute("select pid from info where pid = ?",(ppp,))


要是插入数据 包含特殊字符怎么插入到数据库中?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP