Python 连接数据库
来源:互联网 发布:java 编译流程 编辑:程序博客网 时间:2024/06/05 04:42
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()
- python连接mysql数据库
- python连接mysql数据库
- python连接MySQL数据库
- Python连接mysql数据库
- python--连接数据库篇
- python连接mysql数据库
- Python连接mysql数据库
- Python连接mysql数据库
- Python连接MySql数据库
- Python数据库的连接
- Python 连接mysql数据库
- Python连接数据库-pyodbc
- Python连接数据库
- Python 连接数据库
- python连接mysql数据库
- Python数据库的连接
- Python连接mysql数据库
- Python连接mysql数据库
- 为什么说LD_LIBRARY_PATH不好
- linux函数之htons
- ActivityGroup相关--getLocalActivityManager() 以及intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)用法
- linux shell awk 流程控制语句(if,for,while,do)详细介绍
- Unity3D-RPG项目实战(3):整合Visual Studio 2013开发环境
- Python 连接数据库
- Spring mvc 中MultiActionController的三种methodNameResolver
- ibatis学习笔记-iBatis优缺点总结
- CView中创建CSplitterWnd
- .NET中使用Jquery和Ajax(一)
- SSH tunnel 设置
- 四元数与欧拉角之间的转换
- 使用系统默认声音、震动
- 解决MyEclipse不编译的方法