Skip to content

Instantly share code, notes, and snippets.

@yszou
Created November 11, 2013 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yszou/7415192 to your computer and use it in GitHub Desktop.
Save yszou/7415192 to your computer and use it in GitHub Desktop.
sth about MySQLdb
# -*- coding: utf-8 -*-
import MySQLdb
#(1, 2, 3, 'final', 0)
print MySQLdb.version_info
'''
+--------------------+
|id | email |
+------+-------------+
|admin | xxx@123.com |
+------+-------------+
'''
conn = MySQLdb.Connection(host='localhost', user='test', passwd='', db='Chi')
cursor = conn.cursor()
#确认数据存在
cursor.execute('select * from `User` where id = %s', ('admin', ))
print cursor.fetchall()
#碰巧最后的 SQL 是正确的, 不报错
id_list = [1, 2]
cursor.execute('select * from `User` where id in %s', (id_list, ))
print cursor.fetchall()
#这样就没那么巧了
#id_list = [1]
#cursor.execute('select * from `User` where id in %s', (id_list, ))
#print cursor.fetchall()
#碰巧的 SQL 只对整数有效, 下面的查询并不会得到正确的结果
id_list = ['1', 'admin']
cursor.execute('select * from `User` where id in %s', (id_list, ))
print cursor.fetchall()
#似乎没有比下面更好的办法了
#其实看 django 的 ORM 也可以看出它生成的 SQL 就是这样的
id_list = ['1', 'admin']
cursor.execute('select * from `User` where id in (%s)' % ','.join(['%s'] * len(id_list)),
id_list)
print cursor.fetchall()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment