学习python之编写简单简单连接数据库并执行查询操作

WBOY
Release: 2016-06-10 15:06:05
Original
1144 people have browsed it

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()             #关闭数据库链接
Copy after login

程序执行结果为

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!