Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Python Terhubung Ke Database MySQL Dengan Konektor MySQL &Contoh PyMySQL

Saat Anda ingin terhubung ke database MySQL dalam kode Python, Anda dapat menggunakan keduanya mysql-connector-python Driver MySQL dan PyMySQLmysql-connector-python Driver MySQL adalah driver bawaan server MySQL dan PyMySQL adalah perpustakaan pihak ketiga.

Semua dua perpustakaan python MySQL menyediakan kelas bagi Anda untuk mendapatkan koneksi database MySQL, jalankan insert, delete, update, pilih perintah SQL. Mereka juga mendukung manajemen transaksi. Artikel ini akan menunjukkan kepada Anda contoh cara menggunakan mysql-connector-python dan PyMySQL untuk beroperasi pada tabel database MySQL.

1. Cara Menggunakan mysql-connector-python Untuk Mengoperasikan Database MySQL.

1.1 Instal Perpustakaan mysql-connector-python.

  1. mysql-connector-python library dapat diinstal saat Anda menginstal database MySQL.
  2. Agar Anda dapat menjalankan perintah pip show mysql-connector-python untuk memeriksa apakah sudah terpasang atau belum.
    $ pip show mysql-connector-python
    WARNING: Package(s) not found: mysql-connector-python
  3. Jika mysql-connector-python library tidak diinstal, Anda dapat menjalankan perintah pip install mysql-connector-python untuk menginstalnya.
    $ pip install mysql-connector-python
    Collecting mysql-connector-python
      Downloading mysql_connector_python-8.0.25-py2.py3-none-any.whl (319 kB)
         |████████████████████████████████| 319 kB 219 kB/s 
    Collecting protobuf>=3.0.0
      Downloading protobuf-3.17.0-cp37-cp37m-macosx_10_9_x86_64.whl (959 kB)
         |████████████████████████████████| 959 kB 727 kB/s 
    Requirement already satisfied: six>=1.9 in /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages (from protobuf>=3.0.0->mysql-connector-python) (1.15.0)
    Installing collected packages: protobuf, mysql-connector-python
    Successfully installed mysql-connector-python-8.0.25 protobuf-3.17.0
    
  4. Sekarang ketika Anda menjalankan perintah pip show mysql-connector-python lagi, Anda bisa mendapatkan informasi pemasangannya.
    $ pip show mysql-connector-python
    Name: mysql-connector-python
    Version: 8.0.25
    Summary: MySQL driver written in Python
    Home-page: http://dev.mysql.com/doc/connector-python/en/index.html
    Author: Oracle and/or its affiliates
    Author-email: UNKNOWN
    License: GNU GPLv2 (with FOSS License Exception)
    Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
    Requires: protobuf
    Required-by: 
    

1.2 Gunakan mysql-connector-python Hubungkan Ke Langkah-langkah Database MySQL.

  1. Impor mysql.connector kelas.
    import mysql.connector
  2. Aktifkan mysql.connector.connect() metode untuk terhubung ke server database MySQL.
    # get mysql connection object.
    def open_mysql_connection(user='jerry', password='jerry', host='127.0.0.1', port='3306', database='dev2qa_example', use_unicode=True):
        conn = mysql.connector.connect(user=user, password=password, host=host, port=port, database=database, use_unicode=use_unicode)
        return conn

1.3 Jalankan Pernyataan DDL Untuk Membuat Tabel.

  1. Dapatkan kursor database MySQL.
    cursor = conn.cursor()
  2. Jalankan pernyataan DDL. Jika Anda ingin mengeksekusi beberapa pernyataan DDL sekaligus, Anda harus memisahkan setiap pernyataan DDL dengan titik koma, dan Anda harus menambahkan multi=True
    parameter ke execute() objek kursor metode, jika tidak maka akan memunculkan kesalahan mysql.connector.errors.InterfaceError:Gunakan multi=True saat menjalankan beberapa pernyataan .

    def execute_ddl(conn):
        cursor = conn.cursor()
        
        # The below DDL will first drop the table if exist, then create the table.
        ddl_sql= '''
        
           DROP TABLE user_account;
        
           CREATE TABLE `dev2qa_example`.`user_account` (
          `id` INT NOT NULL AUTO_INCREMENT,
          `user_name` VARCHAR(45) NULL,
          `password` VARCHAR(45) NULL,
          `email` VARCHAR(45) NULL,
          PRIMARY KEY (`id`));
           '''
        # Because the above DDL contains 2 statements ( drop, create), so need to add the multi=True parameter to avoid error mysql.connector.errors.InterfaceError: Use multi=True when executing multiple statements.
        cursor.execute(ddl_sql, multi=True)
        cursor.close()
        
        conn.close()
        
        print(ddl_sql + ' execute successfully.')

1.4 Jalankan Pernyataan DML ( Sisipkan, Perbarui, Hapus ).

  1. Dapatkan objek kursor koneksi database MySQL.
  2. Jalankan penyisipan, perbarui, hapus pernyataan SQL dengan execute() objek kursor metode.
    def execute_dml(conn):
        
        cursor = conn.cursor()
        
        dml_insert = ''' INSERT INTO `dev2qa_example`.`user_account` VALUES (null, %s, %s, %s); ''' 
        
        cursor.execute(dml_insert, ('tom', 'tom12345678', '[email protected]'))
        
        conn.commit()
        
        cursor.close()
        
        conn.close()
    
  3. Jika Anda ingin menyisipkan beberapa baris ke dalam tabel MySQL, Anda dapat menjalankan executemany() objek kursor metode.
    def execute_dml_insert_many(conn):
        
        cursor = conn.cursor()
        
        dml_insert = ''' INSERT INTO `dev2qa_example`.`user_account` VALUES (null, %s, %s, %s); ''' 
        
        row_tuple = (('richard', 'richard', '[email protected]'), ('trump', 'trump', '[email protected]'),('doctor', 'doctor', '[email protected]'))
        
        cursor.executemany(dml_insert, row_tuple)
        
        conn.commit()
        
        cursor.close()
        
        conn.close()

1.5 Jalankan DML Pilih Pernyataan SQL.

  1. Jalankan execute() objek kursor metode untuk menjalankan pilih pernyataan SQL.
    def execute_dml_select(conn):
        
        cursor = conn.cursor()
        
        dml_select = 'SELECT * FROM dev2qa_example.user_account;'
        
        cursor.execute(dml_select)
        
        # print the row header.
        for col in cursor.description:
            
            print(col[0], end='\t')
            
            
        print('\n-----------------------------') 
        
        # print each row data.
        for row in cursor:
            
            print(row)   
            
            print(row[1] + '--->' + row[2])
               
            
        cursor.close()
        
        conn.close()

2. Cara Menggunakan PtMySQL Untuk Mengoperasikan Database MySQL.

2.1 Instal PyMySQL.

  1. Sebelum Anda dapat menggunakan PyMySQL, Anda harus menginstalnya terlebih dahulu. Anda dapat menggunakan pip untuk menginstal seperti di bawah ini.
    $ pip3 install PyMySQL
  2. Anda dapat menjalankan pip3 show perintah untuk memverifikasi instalasi PyMySQL.
    $ pip3 show PyMySQL

2.2 Menggunakan PyMySQL Untuk Menghubungkan Dan Mengoperasikan Database MySQL.

Di bawah ini adalah langkah-langkah menggunakan library PyMySQL dalam kode Python.

  1. Impor PyMSQL koneksi , kursor class.
    from pymysql import connect, cursors
  2. Hubungi hubungkan metode untuk mendapatkan objek koneksi database MySQL.
    conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
  3. Dapatkan objek kursor database dengan fungsi kursor() objek koneksi.
    conn.cursor() as cursor:
  4. Jalankan pernyataan SQL menggunakan objek kursor.
    cursor.execute(sql)
  5. Jika pernyataan sql adalah pernyataan pilih, maka panggil metode fetchall() atau fetchone() objek kursor untuk mendapatkan hasil eksekusi sql. Harap perhatikan setelah memanggil fetchall(), kursor akan pindah ke baris terakhir dari hasil, jadi jika Anda memanggil metode fetchall() lagi, tidak akan ada baris yang dikembalikan.
    row = cursor.fetchall()
    
    or
    
    row = cursor.fetchone()
  6. Jika pernyataan sql adalah pernyataan insert, update, delete, maka panggil fungsi commit() objek koneksi untuk mengkomit perubahan ke database MySQL agar berlaku.
    conn.commit()
  7. Jangan lupa untuk menutup objek koneksi database MySQL di akhir untuk melepaskan sumber daya database.
    if conn is not None:
            conn.close()
            conn = None

2.3 PyMySQL Mengoperasikan Contoh Database MySQL.

  1. Dalam contoh ini, nama database MySQL adalah dev2qa_example , nama tabelnya adalah user_account . Tabel memiliki empat kolom yang id , nama_pengguna , sandi, dan email . Kolom id bertambah secara otomatis.
  2. Kode sumber python berisi metode untuk menyisipkan, memperbarui, menghapus, dan memilih data akun pengguna seperti di bawah ini.
    from pymysql import connect, cursors
    
    global_host='127.0.0.1'
    global_user='jerry'
    global_password='jerry'
    global_db='dev2qa_example'
    global_charset='utf8'
    global_cursorclass=cursors.DictCursor
    
    # get mysql connection object.
    def open_mysql_connection(host='127.0.0.1', user='jerry', password='jerry', db='dev2qa_example', charset='utf8', cursorclass=cursors.DictCursor):
        conn = connect(host=host, user=user, password=password, db=db, charset=charset, cursorclass=cursorclass)
        return conn
        
    # close mysql connection.    
    def close_mysql_connection(conn):
        if conn is not None:
            conn.close()
            conn = None
    
    # execute insert, update or delete sql command.
    def execute_insert_update_delete_sql(sql, host, user, password, db, charset, cursorclass):
        execute_row_count = 0
        conn = None
        print('sql = ' + sql)
        try:
            if string_is_not_empty(sql):
                conn = open_mysql_connection(host, user, password, db, charset, cursorclass)
                with conn.cursor() as cursor:
                    execute_row_count = cursor.execute(sql)
        except Exception as ex:
            print(ex)
        finally:
            if conn is not None:
                conn.commit()
                close_mysql_connection(conn)
            return execute_row_count    
     
    # execute select sql command.                    
    def execute_select_sql(sql, host, user, password, db, charset, cursorclass):
        ret = list()
        conn = None
        print('sql = ' + sql)
        try:
            if string_is_not_empty(sql):
                conn = open_mysql_connection(host, user, password, db, charset, cursorclass)
                with conn.cursor() as cursor:
                    row_count = cursor.execute(sql)
                    print('select return row count = ' + str(row_count))
                    row = cursor.fetchall()
                    print(row)
                    ret.append(row)
        except Exception as ex:
            print(ex)            
        finally:
            if conn is not None:
                close_mysql_connection(conn)
            return ret        
    
    # insert user account to database table dev2qa_example.user_account.                
    def insert_user_account(user_name, password, email):
        print('**********Begin insert_user_account.**********')
        
        if string_is_not_empty(user_name) and string_is_not_empty(password) and string_is_not_empty(email):
            # first check whether user account exist or not.
            sql = "select count(id) as count from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower().strip()+"'"
            row_list = execute_select_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
            
            account_exist = False
            for row in row_list:
                for column in row:
                    exist_count_number = column.get('count')
                    if exist_count_number > 0:
                        account_exist = True
            
            if not account_exist:
                print('User ' + user_name + ' do not exist in database. Insert the user account to database table.')
                sql = "insert into user_account(user_name, password, email) values('"+user_name+"','"+password+"','"+email+"')"
                insert_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
                print('Insert ' + str(insert_row_count) + ' row data successfully.')
            else:
                print('User account exist, can not insert.')    
        else:
            print('user_name, password, email can not be empty.')        
            
        print('**********End insert_user_account.**********')    
       
    # update user account data.            
    def update_user_account(user_name, password, email):
        print('**********Begin update_user_account.**********')
        
        if string_is_not_empty(user_name):
            sql = "update dev2qa_example.user_account set password = '" + password + "', email = '" + email + "' where lower(user_name) = '" + user_name.lower() + "'"
            update_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
        
            if update_row_count == 0:
                print('User account do not exist, insert it now.')
                insert_user_account(user_name, password, email)
            else:
                print('Update ' + str(update_row_count) + ' row data successfully.')
        else:
            print('user_name can not be empty.')        
               
        print('**********End update_user_account.**********')
        
    # delete user account data from database table.    
    def delete_user_account(user_name):
        print('**********Begin delete_user_account.**********')
        
        if string_is_not_empty(user_name):
            sql = "delete from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower()+"'"
            delete_row_count = execute_insert_update_delete_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
            print('Delete ' + str(delete_row_count) + ' row data successfully.')
            
        print('**********End delete_user_account.**********')
        
    # execute select sql command to get user account data by user_name.    
    def get_user_account_by_user_name(user_name):
        print('**********Begin get_user_account_by_user_name.**********')
        sql = "select * from dev2qa_example.user_account where lower(user_name) = '"+user_name.lower().strip()+"'"
        row_list = execute_select_sql(sql, global_host, global_user, global_password, global_db, global_charset, global_cursorclass)
        print('**********End get_user_account_by_user_name.**********')
    
    # check whether the string is empty or not.
    def string_is_not_empty(str):
        if str is None:
            return False
        elif len(str.strip()) == 0:
            return False
        else:
            return True
    
    if __name__ == '__main__':
        # first delete user account jerry.
        delete_user_account('jerry')
        
        # then insert a user account jerry into database.
        insert_user_account('jerry', 'jerry', '[email protected]')
        # show user account data to verify the insert action.
        get_user_account_by_user_name('jerry')
        
        # update usr account information.
        update_user_account('jerry', 'jerry888', '[email protected]')
        # check the updated user account info again.
        get_user_account_by_user_name('jerry')
  3. Di bawah ini adalah hasil eksekusi kode di atas.
    **********Begin delete_user_account.**********
    sql = delete from dev2qa_example.user_account where lower(user_name) = 'jerry'
    Delete 1 row data successfully.
    **********End delete_user_account.**********
    **********Begin insert_user_account.**********
    sql = select count(id) as count from dev2qa_example.user_account where lower(user_name) = 'jerry'
    select return row count = 1
    [{'count': 0}]
    User jerry do not exist in database. Insert the user account to database table.
    sql = insert into user_account(user_name, password, email) values('jerry','jerry','[email protected]')
    Insert 1 row data successfully.
    **********End insert_user_account.**********
    **********Begin get_user_account_by_user_name.**********
    sql = select * from dev2qa_example.user_account where lower(user_name) = 'jerry'
    select return row count = 1
    [{'id': 42, 'user_name': 'jerry', 'password': 'jerry', 'email': '[email protected]'}]
    **********End get_user_account_by_user_name.**********
    **********Begin update_user_account.**********
    sql = update dev2qa_example.user_account set password = 'jerry888', email = '[email protected]' where lower(user_name) = 'jerry'
    Update 1 row data successfully.
    **********End update_user_account.**********
    **********Begin get_user_account_by_user_name.**********
    sql = select * from dev2qa_example.user_account where lower(user_name) = 'jerry'
    select return row count = 1
    [{'id': 42, 'user_name': 'jerry', 'password': 'jerry888', 'email': '[email protected]'}]
    **********End get_user_account_by_user_name.**********

Referensi

  1. Cara Menggunakan MySql Di Mac

  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Belajar MySQL / MariaDB untuk Pemula – Bagian 1

  2. com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:Kegagalan tautan komunikasi

  3. Cara Migrasi dari MSSQL ke MySQL

  4. Perbarui Data di Database MySQL

  5. Bagaimana cara mengubah mysql ke mysqli?