Home > Article > Backend Development > Python operates mysql
1.python 2.7.2 (installation version)
2.MySQL-python-1.2.3.win32-py2.7 (mysqldb module)
#Connect database code
#coding=utf-8
import MySQLdb
import sys
import time
host ='127.0.0.1'
user ='root'
passwd ='123456'
port = 3306
db_list=[]
tb_list=[]
dbcon=MySQLdb.connect(host,user,passwd, port=3306)
cur=dbcon.cursor()
#List all databases
def check_db():
cur.execute('show databases')
for db in cur.fetchall():
db_list.append(db [0])
Return db_list
#Get a list of all tables in the current database
db_list = check_db()
print db_list
#Use the test database to query all tables under the test database
cur.execute("use test")
cur.execute("Select Database()")
print "Current database: %s" %cur.fetchall()[0]
all_table = cur.execute("show tables")
for tb in cur.fetchall( ):
tb_list.append(tb[0])
print tb_list
#Query data table userinfo
userList=[]
cur.execute("use test")
cur.execute("select * from userinfo;")
for shuju in cur.fetchall():
userList.append(shuju)
print userList