SoFunction
Updated on 2024-11-18

How python operates mysql

mysql Usage

Starting services

sudo systemctl start mysql
pip3 install pymysql

python to manipulate the database:

  • define a class
import pymysql

class MyDb():
  def __init__(self, host, user, passwd, db):
      self.__db = (host, user, passwd, db)
      self.__cursor = self.__db.cursor()

  # Additions, deletions, changes -- database
  def set(self, sql):
    try:
      self.__cursor.execute(sql)
      self.__db.commit()
    except Exception as e:
      self.__db.rollback()
      print('Execute Error: \n {e}')

  # Check-database
  def get(self, sql, fetchone=True):
    self.__cursor.execute(sql)
    try:
      if fetchone == True:
        data = self.__cursor.fetchone()
      else:
        data = self.__cursor.fetchall()
    except Exception as e:
      print('Execute Error: \n {e}')
      data = None
    finally:
      return data

  # Close the database
  def close(self):
    self.__db.close()
  • call (programming)
def example():
  ## Instantiate the database
  ### Class parameters: host, user, passwd, db
  db = MyDb('localhost', 'root', 'zuoy123', 'test')
  
  ## View version
  get_version_sql = 'SELECT VERSION()'
  version = (get_version_sql)
  print(f'Database Version: {version}')

  ## Delete table
  delete_table_sql = 'DROP TABLE IF EXISTS employee'
  (delete_table_sql)

  ## New table
  new_table_sql = 'CREATE TABLE IF NOT EXISTS employee( \
    id INT NOT NULL PRIMARY KEY, \
    name CHAR(21) NOT NULL, \
    age DOUBLE DEFAULT 18)'
  (new_table_sql)

  ## Find the table
  get_table_sql = 'SHOW TABLES'
  data = (get_table_sql)
  if data:
    print(data)

  ## Close the database
  ()

if __name__ == '__main__':
  example()

Commonly used sql

DROP TABLE IF EXISTS employee;
CREATE TABLE IF NOT EXISTS employee(id INT);

The above is the step of python operation mysql in detail, more information about python operation mysql please pay attention to my other related articles!