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)
原文地址:https://www.cnblogs.com/cenzhongman/p/7344519.html