Python鏈接MySQL數據庫

鏈接方法

  • 使用 Python DB API(整合了絕大部分的數據庫)
  • 使用 pymysql 包

總體思想

數據庫鏈接對象 connection

數據庫遊標對象 cursor

程序Demo

import pymysql.cursors


class MySQLUtils():
    def executeSQL(self, db, sql):
        connection = pymysql.connect(
            host='118.89.59.181',
            port=3306,
            user='root',
            passwd='ubuntu',
            db=db,
            charset='utf8'
        )

        try:
            with connection.cursor() as cursor:
                cursor.execute(sql)
                connection.commit()
        except:
            print('ERROE While write MySQL')
        finally:
            connection.close()


if __name__ == '__main__':
    sql = 'CREATE TABLE xxx()'
    MySQLUtils().executeSQL(db ='test', sql=sql)
相關文章
相關標籤/搜索