Home >Backend Development >Python Tutorial >Python is a simple way to connect to the database and perform query operations
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
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() #关闭数据库链接
The program execution result is
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!