Python connects to the database operation by doing the following:
In the native MySQL database there is a library named Yao, which has a table named user, the contents of the table
The following is how Python connects to the database and finds out what is in the table, with the following code:
#! /usr/bin/python# filename conn.pyimport mysqldb # Load Connection Database module try : # Attempt to connect to database conn = MySQLdb.connect ("localhost", "root", "www", "Yao", charset= "UTF8") # defines the information that connects the database except Mysqldb.operationalerror, Message: # connection failure prompt print "link error" cursor=conn.cursor () #定义连接对象cursor. Execute ("SELECT * from User") #使用cursor提供的方法来执行查询语句data =cursor.fetchall () #使用fetchall方法返回所有查询结果print data #打印查询结果cursor. Close ( ) #关闭cursor对象conn. Close () #关闭数据库链接
The result of the program execution is