Python3.0 操作MySQL數據庫執行SQL語句


py3不支持MySQLdb,需要導入pymysql模塊
 1 # coding: utf-8
 2 # Team : Quality Management Center
 3 # Author:Carson
 4 # Date :2019/6/20 17:52
 5 # Tool :PyCharm
 6 
 7 import pymysql
 8 
 9 
10 class MysqldbHelper(object):
11 
12     def __init__(self, host='數據庫地址', username='登錄名', password='密碼', port='端口',  database='庫名稱', charset='utf8'):
13         self.host = host
14         self.username = username
15         self.password = password
16         self.database = database
17         self.port = port
18         self.con = None
19         self.cur = None
20         self.charset = charset
21         try:
22             self.con = pymysql.connect(host=self.host, user=self.username, passwd=self.password, port=self.port, db=self.database)
23             # 所有的查詢,都在連接 con 的一個模塊 cursor 上面運行的
24             self.cur = self.con.cursor()
25         except:
26             print("DataBase connect error,please check the db config.")
27 
28     def execute(self, sql):
29 
30         sql = sql
31         try:
32             self.cur.execute(sql)
33             results = self.cur.fetchall()
34             print(results)
35             self.cur.close()
36         except pymysql.Error as e:
37             error = 'MySQL execute failed! ERROR (%s): %s' % (e.args[0], e.args[1])
38             print(error)
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM