python联接mysql

 

下载MySQL_python-1.2.2-py2.5-win32.egg

拷目录下mysqldb,_mysql_py,_mysql_pyd,_mysql_exce..到site_packages目录下

#-*- encoding: gb2312 -*-

import os, sys, stringPHPChina 开源社区门户)R It,Odx.[
import MySQLdbPHPChina 开源社区门户*l(de B)ty}I!yD E
#导入mysqldb模块

#建立数据联接

try:
}9} /;x qB7388    conn = MySQLdb.connect(host='localhost',user='root',passwd='root',db='test')PHPChina 开源社区门户0WI9WS9@0i
except Exception, e:
}i1|F2}9rE7388    print e
4[~3]f4K+K9Q!{:x7388    sys.exit()

#获得句枸

cursor = conn.cursor()

#下面的SQL你会吧

sql = "INSERT INTO topics (tid, subject, content) VALUES ('', 'test', 'hongfu')";

cursor.execute(sql)

sql = "SELECT * FROM test LEFT JOIN topics ts USING(t_id) WHERE ts.t_id > 10";

#执行

cursor.execute(sql)PHPChina 开源社区门户J0l9j UBW�n4Q
#查出所有记录

alls = cursor.fetchall()

if alldata:PHPChina 开源社区门户F*RSd uH!{,i"b+B
    for rec in alls:
8WGc ?F]7388        print rec[0], rec[1]

#关闭句枸

cursor.close()

关闭数据联接

conn.close()

你可能感兴趣的:(python联接mysql)