学习python 第三季:编写简单简单连接数据库并执行查询操作

 python 连接数据库操作, 方法如下:

在本机的mysql 数据库中有一个名为yao的库,其中有一个名为user的表,表中的内容如图

 

下面,则是python连接数据库的方法,及查找出表中的内容,代码如下:

#! /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()                    #定义连接对象

cursor.execute("select * from user")   #使用cursor提供的方法来执行查询语句

data=cursor.fetchall()                 #使用fetchall方法返回所有查询结果

print data                            #打印查询结果

cursor.close()                        #关闭cursor对象

conn.close()                          #关闭数据库链接

 

程序执行结果为

 

 

你可能感兴趣的:(职场,数据库连接,休闲)