python连接数据库
1、 下载MySQLdb模块并安装
apt-get install MySQLdb
2、 导入MySQLdb模块
import MySQLdb
3、 用MySQLdb.connect建立数据库连接
Conn =MySQLdb.connect(host,user,passwd,db )
如:conn=MySQLdb.connect("localhost","root", "yuanhui", "Exon")
其他参数:
charset:数据库编码,一般为utf8。//可以避免中文问题。
conv,将文字映射到Python类型的字典。默认为MySQLdb.converters.conversions
cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。
compress,启用协议压缩功能。
named_pipe,在windows中,与一个命名管道相连接。
init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。
read_default_file,使用指定的MySQL配置文件。
read_default_group,读取的默认组。
unix_socket,在unix中,连接使用的套接字,默认使用TCP。
port,指定数据库服务器的连接端口
4、 执行SQL语句
sql=”select content form Task”
cursor = conn.cursor()
cursor.execute(sql)
5、 接收返回值
row=cursor.fetchall ()
6、 关闭curse和数据库的连接。
cursor.close(); conn.close()
源代码:1 #!/usr/bin/python
2 #decoding=GBK
3
4 import sys
5
6 reload(sys)
7 sys.setdefaultencoding('GBK')
8
9 print 'Content-Type: text/html;charset=GBK\r\n'
10
11
12 import MySQLdb
13
14 conn=MySQLdb.connect("localhost","root", "jhsdfgs", "dsfhg", charset=”GBK”)
15
16 sql=("select Brief from Affair")
17
18 cursor=conn.cursor()
19 cursor.execute(sql)
20 row=cursor.fetchall ()
21 for rowLine in row:
22 for rowValue in rowLine:
23 print rowValue
24 cursor.close()
25 conn.close()