article directory
-
- overview li>
- python connection MySQL li>
- python connection PostgreSQL li> ul>
overview h2>
in general, when using python to connect to a database, I like to define a Class to facilitate the subsequent use of
Class: a collection of objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
can be likened to a Word template that you can use every time you create a new Word file, which is handy for frequently used scenariosconnects to the database to execute commands and return results and then disconnects, as is often the case when writing scripts, so define a class
python connection MySQL h2>
connects to MySQL using pymysql
class cnMySQL: def __init__(self): self._dbhost = '172..16.56.2' self._dbuser = 'dba' self._dbpassword = 'dba1' self._dbname = 'test' self._dbcharset = 'utf8' self._dbport = int(3306) self._conn = self.connectMySQL() if (self._conn): self._cursor = self._conn.cursor(cursor=pymysql.cursors.DictCursor) def connectMySQL(self): try: conn = pymysql.connect(host=self._dbhost, user=self._dbuser, passwd=self._dbpassword, db=self._dbname, port=self._dbport, cursorclass=pymysql.cursors.DictCursor, charset=self._dbcharset) except Exception as e: raise #print("数据库连接出错") conn = False return conn def close(self): if (self._conn): try: if (type(self._cursor) == 'object'): self._conn.close() if (type(self._conn) == 'object'): self._conn.close() except Exception: print("关闭数据库连接异常") def ExecQuery(self,sql,*args): """ 执行查询语句 """ res = '' if (self._conn): try: self._cursor.execute(sql,args) res = self._cursor.fetchall() except Exception: res = False print("查询异常") self.close() return res
use method :
first call: conn = cnMySQL()
execute SQL example: test_sql = conn.ExecQuery(” select * from test where id = %s; Canshu)
returns a listcontaining dict when the data is returned
python connection PostgreSQL h2>
connects to PG using the package psycopg2
class PGINFO: def __init__(self,host, user, pwd, db, port): self.host = host self.user = user self.pwd = pwd self.db = db self.port = port def __GetConnect(self): """ 得到连接信息 返回: conn.cursor() """ if not self.db: raise(NameError, "没有设置数据库信息") self.conn = psycopg2.connect(database=self.db, user=self.user, password=self.pwd, host=self.host, port=self.port) cur = self.conn.cursor() if not cur: raise (NameError, "连接数据库失败") else: return cur def ExecQuery(self, sql): """ 执行查询语句 """ if sql == 'close': self.conn.close() else: cur = self.__GetConnect() cur.execute(sql) # resList = cur.fetchall() return cur
is called first, where
using the parameter file is called
pg = PGINFO(host=host_cus, user=user_cus, pwd=pwd_cus, db=db_cus, port=port_cus)
executes the command, fetching the returned result
cur = pg.ExecQuery("show data_directory;") pgdata = cur.fetchone()
div>
Read More:
- Python traverses all files under the specified path and retrieves them according to the time interval
- Python recursively traverses all files in the directory to find the specified file
- The Python DOM method iterates over all the XML in a folder
- Python automatically generates the requirements file for the current project
- Python Connect database error: command listdatabases requires authentication
- Python: How to Reshape the data in Pandas DataFrame
- You can run the Ansible Playbook in Python by hand
- Change the Python installation path in Pycharm
- Python+ Pandas + Evaluation of Music Equipment over the years (Notes)
- [Solved] Python Keras Error: AttributeError: ‘Sequential‘ object has no attribute ‘predict_classes‘
- Python Error aiohttp.client_exceptions.ClientConnectorCertificateError, Cannot connect to host:443
- [Solved] Jupyter Notebook Error: SparkException: Python worker failed to connect back
- Pychar can’t connect to Python console, but it can run. Py file, and Anaconda’s command line can run Python command
- Design python+mysql database with multi-level menu directory
- Invalid python sd, Fatal Python error: init_fs_encoding: failed to get the Python cod [How to Solve]
- How to Solve Python WARNING: Ignoring invalid distribution -ip (e:\python\python_dowmload\lib\site-packages)
- [Solved] NPM install Error: check python checking for Python executable python2 in the PATH
- [Solved] opencv-python: recipe for target ‘modules/python3/CMakeFiles/opencv_python3.dir/all‘ failed
- [Solved] Saving to Database Error: pymysql.err.DataError: (1366, “Incorrect string value…
- Python Error: pip install mysql-connector-python failed