python查询mysql数据库
import pymysqlhost = '192.168.74.5'user = 'root'passwd ='root'port = 3310db = 'dingding' #数据库名称table = 'gl_user'class SelectMySQL(object): def select_data(self,sql): result = [] try: self.conn = pymysql.connect( host = host, port = port, user = user, passwd = passwd, db = db, charset='utf8', ) self.cur = self.conn.cursor() self.cur.execute(sql) alldata = self.cur.fetchall() for rec in alldata: print(rec) result.append(rec) except Exception as e: print('Error msg:',e) return result def closeMysql(self): self.cur.close() self.conn.close()if __name__ =='__main__': sql = 'select * from gl_user' select = SelectMySQL() result1 = select.select_data(sql) select.closeMysql() print(result1)
import pymysql as MySQLdbhostname = '192.168.74.5'user = 'root'passwd = 'root'port = 3310db = 'dingding'table = 'gl_user'class MYSQLCommand(object): def __init__(self,host,port,user,passwd,db,table): self.host = host self.port = port self.user = user self.passwd = passwd self.db = db self.table = table def connectMysql(self): try: self.conn = MySQLdb.connect(host=self.host,port=self.port,user=self.user,passwd=self.passwd,db=self.db,charset='utf8') print(self.conn) self.cursor =self.conn.cursor() except: print('connect mysql error') def queryMysql(self): sql = 'select * from '+self.table try: self.cursor.execute(sql) row = self.cursor.fetchall() print(row) except: print(sql,' execute failed') def closeMysql(self): self.cursor.close() self.conn.close()if __name__=='__main__': mysql = MYSQLCommand(hostname,port,user,passwd,db,table) mysql.connectMysql() mysql.queryMysql() mysql.closeMysql()