python2
MySQLdb
just usecode show as below
class sql(object): def __init__(self): try: self.conn = MySQLdb.connect( host=DB_IP, user=DB_USER, passwd=DB_PASSWORD, db=DB_NAME, ) self.conn.set_character_set('utf8') self.cur = self.conn.cursor() self.cur.execute('SET NAMES utf8;') self.cur.execute('SET CHARACTER SET utf8;') self.cur.execute('SET character_set_connection=utf8;') except Exception as e: raise e # 返回二维元组,每一条记录作为一个元组,所有的记录再组成一个元组 def executeQuery(self, sqlcode): try: self.cur.execute(sqlcode) resultSet = self.cur.fetchall() self.conn.commit() return resultSet except Exception as e: self.conn.rollback() raise e def executeUpdate(self, sqlCode): try: self.cur.execute(sqlCode) self.conn.commit() except Exception as e: self.conn.rollback() raise e def __del__(self): self.conn.close()
python3
use pymysql
db=pymysql.connect(host="192.168.1.102",user="root",password="123456",database="fwwb",charset='utf8') cursor = db.cursor()
- When the query result contains Chinese, you need to specify the
charset
parameters, otherwise there will be garbled characters - When writing the result to the document, the open function needs to add
encoding
a parameter to specify the encoding Inquire
results = cursor.fetchall() #返回所有结果 data = cursor.fetchone() #返回单条数据