Python is a simple way to connect to the database and perform query operations

高洛峰
Release: 2017-03-07 16:28:55
Original
1574 people have browsed it

Python connects to the database operation, the method is as follows:

There is a library named yao in the mysql database of this machine, which has a table named user. The contents of the table are as shown in the figure

Python is a simple way to connect to the database and perform query operations

Below is how python connects to the database and finds out the contents of the table. The code is as follows:

#! /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

The program execution result is

Python is a simple way to connect to the database and perform query operations

For more related articles about writing simple python to connect to the database and perform query operations, please pay attention to the PHP Chinese website!

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!