Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to configure python3 file and mysql database connection configuration

Shulou Source: shulou.com Published: 2022-06-02 06:28:03 09月11日 Update

This article introduces the relevant knowledge of "how to configure python3 file and mysql database connection configuration". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Good habits should be formed, and database-related configurations are generally placed in the configuration file.

1. Configuration file

It is generally named config.ini, and the contents are as follows:

[mysql]

Db.name=databasename

Db.user = root

Db.host = 10.10.xx.xx

Db.port = 3306

Db.password = xx

2. Configuration file read substitution code

The read function is named DBUtil.py

Import configparser

Import os

Class DBUtil (object):

_ _ db_host=''

Def _ init__ (self):

Path = os.path.dirname (os.path.dirname (os.path.abspath (_ _ file__)

Config = configparser.ConfigParser ()

Config.read (path+ "/ xx/config.ini", encoding= "utf-8")

Config.sections () # get section node

Config.options ('mysql') # gets the options of the specified section, that is, all the keys of the node

Self.__db_name=config.get ('mysql', "db.name")

Self.__db_host=config.get ('mysql', "db.host")

Self.__db_port=config.getint ('mysql', "db.port")

Self.__db_user=config.get ('mysql', "db.user")

Self.__db_password=config.get ('mysql', "db.password")

Def getName (self):

Return self.__db_name

Def getHost (self):

Return self.__db_host

Def getPort (self):

Return self.__db_port

Def getUser (self):

Return self.__db_user

Def getPassword (self):

Return self.__db_password

3. Make a connection

For the time being, there is no encapsulation for database connection and release, but this is just a brief demonstration.

From pymysql import *

From xx.DBUtil import DBUtil

DbUtil = DBUtil ()

Conn=connect (host=dbUtil.getHost (), user=dbUtil.getUser (), passwd=dbUtil.getPassword ())

, db=dbUtil.getName (), port=dbUtil.getPort (), charset='utf8')

Cur=conn.cursor () # get a cursor

. . . Business code

Cur.close () # close the cursor

Conn.close () # release database resources

This is the end of the content of "how to configure python3 file and mysql database connection configuration". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Configuration data database file content code more cursors knowledge nodes practical good learned and then business function just dilemma actual situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Linux Huawei NVidia Redmi