Python2
- can be used
MySQLdb
The code is as follows
classsqlObject):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 asE:RaiseE# Returns a two-dimensional tuple, each record as a tuple, and all the records to form a tuple defExecuteQuery ( Self, Sqlcode):Try: Self. Cur.execute (Sqlcode) ResultSet= Self. Cur.fetchall () Self. Conn.commit ()returnResultSetexcept Exception asE: Self. Conn.rollback ()RaiseEdefExecuteupdate ( Self, SqlCode):Try: Self. Cur.execute (SqlCode) Self. Conn.commit ()except Exception asE: Self. Conn.rollback ()RaiseEdef __del__( Self): Self. Conn.close ()
Python3
Using Pymysql
db=pymysql.connect(host="192.168.1.102",user="root",password="123456",database="fwwb",charset=‘utf8‘= db.cursor()
Specify the parameter name when the parameter is relatively long, or you will get an error
- Specify parameters when the query results contain Chinese
charset
, otherwise garbled characters will appear.
- When you write the results to a document, the Open function adds a parameter to the
encoding
specified encoding
Inquire
=#返回所有结果=#返回单条数据
Python Connection Database