# This is mainly recorded configuration parameters and parameter passing method of connecting a simple query mysql database
Import pymysql
class readSQL (Object):
"" "action class MySql database" ""
DEF the __init __ (Self):
# establish a connection
self.connect = pymysql.connect (host = mysql [ 'mysql '] [ 'host'], # database address
port = mysql [ 'mysql'] [ 'port'], # ports
user = mysql [ 'mysql'] [ 'user'] # login username
password = mysql [ 'mysql'] [ 'password'], # password
database = mysql [ 'mysql'] [ 'database'], # choose to connect to the database
use_unicode = mysql [ 'mysql'] [ 'use_unicode '], # encoding format: set to True
charset = mysql [ 'mysql'] [ 'charset']) # encoding format: UTF8
# use_unicode and chaeset need to be set in order to make the check out the Chinese data is not garbled
# Create a cursor
self.cur = self.connect.cursor () # operation of the database is to operate through the cursor
DEF find_one (Self, SQL):
"" "
queries a statement
: param sql: SQL statement
: return: inquiry the results
"" "
self.connect.commit () # to-date data in the database synchronization (because if not commit, then update the database after the data, queries to the original data will be specifically explained below)
Self. cur.execute (SQL)
return self.cur.fetchone () # database operations performed by a cursor, either fetchone where a query method is pymysql library
DEF Close (Self):
"" "
Close cursor mysql connection, disconnect from the database link method
: return:
"" "
self.cur.close () # turn off the cursor
self.connect.close () # and then disconnect the database link
if __name__ == '__main__':
. mysql_01 = ReadSql () find_one ( sql = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX;") # this query Oracle database connection and query cx_Oracle bit different, here is the statement may not add; No.
Print (mysql_01)
# Why do we need before each query commit () about it?
Here can be simply understood, when after pymysql connect to the database after the connection is completed, if the data in the database is a camera, the data is dead. Every time data is read from this picture will look, even if the data is updated, the query to the data on still pictures. Therefore commit () is the equivalent data synchronization database.
# Configuration information for the database connection I was Yaml configuration file, it is stored in a database by reading the configuration file is stored in Yaml to pass the Senate.
search result: