免费注册 查看新帖 |

Chinaunix

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

cursor.execute()执行反斜杠的问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-04-24 17:10 |只看该作者 |倒序浏览
本帖最后由 ilikeqdi 于 2012-04-24 17:11 编辑

#!/usr/bin/python
import MySQLdb
db=MySQLdb.connect(host="localhost",user="root",passwd="",db='test')
cursor=db.cursor()
cursor.execute(r'show databases \G;')
result=cursor.fetchall()
cursor.close()
print result

Traceback (most recent call last):
  File "./test.py", line 5, in ?
    cursor.execute(r'show databases \G;')
  File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 174, in execute
  File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler
_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 '\\G' at line 1")

换成cursor.execute('show databases \\G;')
还是不行
谁有什么好办法??

论坛徽章:
0
2 [报告]
发表于 2012-04-24 18:34 |只看该作者
试了下貌似没问题:
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-

  3. import sys
  4. import MySQLdb


  5. def myprint(obj, end='\n'):
  6.     sys.stdout.write(str(obj) + end)


  7. def main():
  8.     db = MySQLdb.connect(host='localhost', user='root',
  9.                          passwd='', db='mysql')
  10.     cursor = db.cursor()
  11.     cursor.execute(r'show databases')
  12.     result = cursor.fetchall()
  13.     myprint(result)

  14.     cursor.execute(r'use test')
  15.     cursor.execute(r'show tables')
  16.     result = cursor.fetchall()
  17.     myprint(result)

  18.     cursor.close()


  19. if __name__ == '__main__':
  20.     main()
  21.     myprint('done')
复制代码

论坛徽章:
0
3 [报告]
发表于 2012-04-24 20:39 |只看该作者
cursor.execute(r'show databases \G;')


\G 是重点

论坛徽章:
0
4 [报告]
发表于 2012-04-24 21:03 |只看该作者
不懂\G的用处,只是看了下输出似乎比较美观一点。
换成直接执行操作系统命令呢
  1. C:\>mysql -u root -p -e "show databases\G"
  2. Enter password: *********
  3. *************************** 1. row ***************************
  4. Database: information_schema
  5. *************************** 2. row ***************************
  6. Database: mysql
  7. *************************** 3. row ***************************
  8. Database: test
复制代码

论坛徽章:
0
5 [报告]
发表于 2012-04-25 09:41 |只看该作者
直接执行系统命令是可以实现的.就是想弄明白怎么才能cursor.execute() 包含\的语句,baidu,google了很久了,也没成功

论坛徽章:
0
6 [报告]
发表于 2012-04-26 22:33 |只看该作者
如此冷清

论坛徽章:
0
7 [报告]
发表于 2012-04-27 08:59 |只看该作者
是啊,非常冷清,似乎都没见过这个板块的版主们来发帖回帖。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP