MySQLdb.connect()怎么传一个字典进去,为什么我按下面的代码传,无法连接

2016-01-09 21:15:44 +08:00
 scott123

db_dict=dict(host="127.0.0.1",user="root",passwd="test",db="test1")
def insert_one_data(self,sql,*params):
try:
conn=MySQLdb.connect(db_dict)
cur=conn.cursor()
cur.execute("INSERT INTO admininfo(username,passwd) VALUES(%s,%s)",params)
conn.commit
except MySQLdb.Error,e:
print e
sys.exit(1)
finally:
if conn:
cur.close()
conn.close()

3313 次点击
所在节点    Python
6 条回复
neoblackcap
2016-01-09 21:44:40 +08:00
cur.execute("INSERT INTO admininfo(username,passwd) VALUES(%s,%s)",*params)试试
scott123
2016-01-09 21:55:02 +08:00
我的主要问题是我要使用 db_dict 作为参数连接到数据库,而不是使用以下的 code
conn=MySQLdb.connect("127.0.0.1","root","test","test1")
那么以后我只要修改 db_dict 这个参数就可以连接到不同当数据库了,我见到过别人这么实用过,但是我怎么搜索也是找不到
Zzzzzzzzz
2016-01-09 21:56:24 +08:00
MySQLdb.connect(**db_dict)
neoblackcap
2016-01-09 22:17:38 +08:00
@scott123 支持三楼,刚才急着上厕所,没细看
scott123
2016-01-09 22:23:21 +08:00
import MySQLdb
db_dict=dict(host="127.0.0.1",user="root",passwd="dushibing555",db="test1")
conn=MySQLdb.connect(**db_dict)
cur=conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("SELECT passwd from admininfo WHERE username=%s",('jerry',))
rows=cur.fetchall()
print rows

successfull!
能解释一下吗?新手不太懂,我知道参数前加两个**代表是参数是字典,那么是不是说如果不加**号解释器无法识别它是一个字典,所以无法正确的解释参数。
neoblackcap
2016-01-09 22:40:20 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/249577

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX