在本机的mysql 数据库中有一个名为yao的库,其中有一个名为user的表,表中的内容如图
下面,则是python连接数据库的方法,及查找出表中的内容,代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#! /usr/bin/python
# filename conn.py
import MySQLdb # 载入连接数据库模块
try : # 尝试连接数据库
conn = MySQLdb.connect( "localhost" , "root" , "www" , "yao" ,charset = "utf8" ) # 定义连接数据库的信息
except MySQLdb.OperationalError, message: # 连接失败提示
print "link error"
cursor = conn.cursor() #定义连接对象
data = cursor.fetchall() #使用fetchall方法返回所有查询结果
print data #打印查询结果
cursor.close() #关闭cursor对象
conn.close() #关闭数据库链接
|
程序执行结果为