1. 程式人生 > >python呼叫mysql的api

python呼叫mysql的api

import MySQLdb
class MysqlApi(object):
    def __init__(self):
        pass
    def information(self):
        return "this a python way use mysqldb api!"
    def look_database_verson(self):
        conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
        cur=conn.cursor()
        cur.execute("SELECT VERSION()")
        data= cur.fetchall()
        #data= cur.fetchone()
        verson=data[0][0]
        cur.close()
        conn.close()
        return verson
    def look_database(self):
        dalist=[]
        
        conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',port=3306)
        cur=conn.cursor()
        cur.execute("SHOW DATABASES")
        data= cur.fetchall()
        #data= cur.fetchone()
        for p in data:
            dalist.append(p[0])
        cur.close()
        conn.close()
        return dalist
    def create_database(self,prodb):
        conn=MySQLdb.connect(host='localhost',user='root',passwd="123456",port=3306)
        cur=conn.cursor()
        try:
            sql=('create database '+prodb)
            cur.execute(sql)
            return prodb
        except:
            return "database have been exists!"
        cur.close()
        conn.close()
        
    def delete_database(self,prodb):
        try:
            conn=MySQLdb.connect(host='localhost',user='root',passwd="123456",db=prodb,port=3306)
            cur=conn.cursor()
            cur.execute('drop database '+prodb)
            cur.close()
            conn.close()
            return prodb
        except:
            return "database in not exists!"
    def rename_database(self,prodbold,prodbnew):
        #haven't success
        pass
    
        
        
        
    
             

    
        
ap=MysqlApi()
#print ap.information()
#print ap.look_database_verson()
#print ap.look_database()
#print ap.delete_database("root")
#print ap.create_database("root1")
print ap.rename_database("test",'root')

要求安裝python、mysql、MySQLdb模組。
目前只寫了說明、檢視資料庫版本、檢視資料庫、刪除資料庫、建立資料庫。