1. 需要模块mysqldb
2. 如果mysql整体安装在/usr/local下则需要建立so文件的软链接,比如:
ln -s /usr/local/mysql/lib/libmysqlclient.so.20 /usr/lib/libmysqlclient.so.20
3.测试代码
-
import MySQLdb
-
db = MySQLdb.connect("210.14.154.210","root","goumin123","new_dog123",3308);
-
cursor = db.cursor();
-
cursor.execute("SELECT * from notebook limit 0,1");
-
data = cursor.fetchone();
-
print data;
-
db.close();
4. 中文读取乱码,需要调整
确保python代码编码,python sys编码,数据库编码一致即可
同时在数据库结果集直接print时,会显示/u的unicode编码。单独取出内容时,就不会,直接是可显示的字符串
注意sys在set前需要reload一下
-
#encoding=utf-8
-
import sys
-
import MySQLdb
-
reload(sys)
-
sys.setdefaultencoding('utf-8');
-
-
db = MySQLdb.connect("210.14.154.210","root","goumin123","new_dog123",3308,charset='utf8');
-
cursor = db.cursor();
-
cursor.execute("SELECT subject,authorid from pre_forum_thread limit 0,1");
-
data = cursor.fetchall();
-
print data[0][0];
-
db.close();
-
f=open("/tmp/3",'w');
-
f.write(data[0][0]);
-
f.close();
阅读(821) | 评论(0) | 转发(0) |