Python中直接在MySQL執行SQL命令

因爲懶,所以不想用SQLyog,用Python寫了一個快速執行SQL命令的程序:

import pymysql,sys

class dealMySQL(object):
    'PyMysql'
    version = 'Version:0.1' 
    author = 'Author: August'
    
    def __init__(self):
        pass
    
    @classmethod    
    def execute(self,sql):
        'execute SQL command!'
        try:
            conn = pymysql.Connect(host='localhost',user='root',passwd='',db='sql_',port=3306,charset='utf8')
            cur = conn.cursor()
        except pymysql.err.InternalError as err:
            print("Can not connect MySQL:%r"%err)
            sys.exit()
        except pymysql.err.OperationalError as err:
            print("Can not connect MySQL:%r"%err)
            sys.exit()
        try:
            cur.execute(sql)
            conn.commit()
            for x in cur:
                print(x)
            print("success!")
        except:
            print("Error! Please check your SQL!")
            
        cur.close()
        conn.close()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章