python操作mySQL数据库

今天的内容主要是python使用pymysql操作mysql数据库,之后会在这个的基础之上编写读取配置文件

直接看python连接mysql的代码:

  

 1 import pymysql
 2 
 3 class connectMySQL(object):
 4     def  __init__(self,hostname,user,password,dbname,port):
 5         db_config = {
 6             'host': hostname,
 7              'port': port,
 8              'user': user,
 9              'password': password,
10              'db': dbname
11             }
12         self.conn = pymysql.connect(**db_config)
13     def get_cursor(self):
14         return self.conn.cursor()
15 
16     def querydb(self,sqlstring):
17         cursor = self.get_cursor()
18         try:
19             cursor.execute(sqlstring)
20             results = cursor.fetchall()
21             for row in results:
22                 print(row)
23         except:
24             self.logger.error('Error:unable to fetch data')

 

posted @ 2018-08-06 14:28  jiyanjiao  阅读(216)  评论(0编辑  收藏  举报