python+selenium 連線MySQL資料庫

aiee發表於2018-08-08
import pymysql as pymysql

class MySql(object):
    def mysql(sql):
        #連線資料庫
        hostvalue='localhost'
        uservalue='root'
        passwordvalue='123456'
        dbvalue='test'
        portvalue=3306
        connection = pymysql.connect(host=hostvalue, user=uservalue, password=passwordvalue, db=dbvalue, port=portvalue, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

        # 通過cursor建立遊標
        cursor = connection.cursor()
        # 建立sql 語句,並執行
        sqlvalue = sql #"select * from user"
        cursor.execute(sqlvalue)
        result = cursor.fetchone() #查詢資料庫單條資料
        #result = cursor.fetchall() #查詢資料庫多條資料
        #提交sql
        connection.commit()
        return result

    if __name__ == '__main__':
        a=mysql(sql="select * from user")
        print(a)
        b=mysql(sql="select name from user where id='213'")
        print(b)
        mysql(sql="update user set name='哈哈' where studentid=23")

相關文章