Created
November 11, 2013 15:42
-
-
Save yszou/7415192 to your computer and use it in GitHub Desktop.
sth about MySQLdb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import MySQLdb | |
#(1, 2, 3, 'final', 0) | |
print MySQLdb.version_info | |
''' | |
+--------------------+ | |
|id | email | | |
+------+-------------+ | |
|admin | [email protected] | | |
+------+-------------+ | |
''' | |
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