0%

python连接mysql

安装MySQLdb

1
pip install mysql-python

创建连接

1
2
3
4
5
6
def db_get_conn(**dbconfig):
conn = MySQLdb.connect(**dbconfig)
cursor = conn.cursor()
return conn, cursor

conn, cursor = db_get_conn(host="127.0.0.1", user="root",passwd=“123", db=“db_haha",charset="utf8")

创建查询

1
cursor.execute("select a,b from t_hehe")

获取结果

1
2
3
4
5
6
for a, b in cursor.fetchall():
print a,b

// 注意:如果只有1个元素,这样才行
for (a,) in cursor.fetchall():
print a

如果结果太大,不想全部拉回来,而是创建好查询,现在服务器端查好结果,再一条条拉回来,要这样创建连接

1
2
3
4
5
6
def db_get_ss_conn(**dbconfig):
ss_conn = MySQLdb.connect(**dbconfig)
ss_cursor = conn.cursor(cursorclass=MySQLdb.cursors.SSCursor)
return ss_conn, ss_cursor

ss_conn, ss_cursor = db_get_conn(host="127.0.0.1", user="root",passwd=“123", db=“db_haha",charset="utf8")

然后这样获取结果

1
2
3
ss_cursor.execute("select a,b from t_hehe")
for a,b in ss_cursor:
print a, b

最后修改的话,记得提交事务

1
conn.commit()