Hướng dẫn mysql commit python - mysql cam kết python

Bài trước mình đã hướng dẫ mọi người cách cài đặt và kết nối Python đến MySQL rồi. Bài này mình sẽ hướng dẫn mọi người cách thực thi truy vấn MySQL trên Python.

Trong package PyMSQL mọi thao tác, tác động đến MySQL đều nằm ở trong object cursor, chính vì vậy sau khi kết nối thành công đến MySQL thì chúng ta sẽ chỉ tập chung vào cursor object thôi.

Hơn nữa để phù hợp với nguyên tắc open-close thì mình sẽ lợi dụng đặc thù của try catch để có thể auto đóng kết nối khi không dùng nữa. Bằng cách cho phương thức

cursor.execute(query, params)
0 vào
cursor.execute(query, params)
1.

VD::

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
# to do
finally:
    # close connection
    connection.close()

1, Phương thức execute().

Phương thức

cursor.execute(query, params)
2 có tác dụng thức thi các truy vấn MySQL. sử dụng với cú pháp:

cursor.execute(query, params)

Trong đó:

  • cursor.execute(query, params)
    3 là nội dung câu truy vấn mà bạn muốn thực thi trên MySQL.
  • cursor.execute(query, params)
    4 là một
    cursor.execute(query, params)
    5,
    cursor.execute(query, params)
    6,
    cursor.execute(query, params)
    7 chứa các tham số mà bạn muốn parse vào câu
    cursor.execute(query, params)
    3. Tham số này có thể bỏ trống.

Hàm này sẽ trả về số dòng dữ liệu (row) bị ảnh hưởng bởi câu truy vấn.

VD: Mình sẽ tạo database có tên 

cursor.execute(query, params)
9 bằng Python.: Mình sẽ tạo database có tên 
cursor.execute(query, params)
9 bằng Python.

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()

Nếu như kết quả trả về là 1 thì là bạn đã tạo thành công database.

2, Phương thức executemany(),

Phương thức này về cú pháp thì tương tự như phương thức

cursor.execute(query, params)
2, chỉ khác là nó có khả năng làm ảnh hưởng nhiều dòng dữ liệu trên 1 câu query.

Cú pháp:

cursor.executemany(query, params)

Các tham số và kết quả trả về giống như phương thức

cursor.execute(query, params)
2.

VD: Mình sẽ tạo 1 table trong MySQL qua phương thức

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
2.: Mình sẽ tạo 1 table trong MySQL qua phương thức
import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
2.

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '', 'pymysql')

try:
    with connection.cursor() as cursor:
        # create a table
        query = """
            CREATE TABLE `users` (
                `id` int(11) NOT NULL AUTO_INCREMENT,
                `email` varchar(255) NOT NULL,
                `password` varchar(255) NOT NULL,
                PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8
            AUTO_INCREMENT=1
        """
        cursor.execute(query)

finally:
    # close connection
    connection.close()

3, Phương thức commit().

Do mặc định thì connection không tự động commit thay đổi nên bạn cần phải sử dụng phương thức

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
3 để thực hiện commit data khi có thay đổi.

Chú ý: Phương thức

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
3 này nằm trong object connection.  Phương thức
import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
3 này nằm trong object connection. 

VD: Mình sẽ thực thi insert dữ liệu vào table

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
5 mà mình vừa tạo ở trên.: Mình sẽ thực thi insert dữ liệu vào table
import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
5 mà mình vừa tạo ở trên.

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '', 'pymysql')

try:
    with connection.cursor() as cursor:
        # insert a user
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('[email protected]', '123456'))

        # commit
        connection.commit()
        
finally:
    # close connection
    connection.close()

4, Phương thức autocommit().

Để không phải lúc nào cũng phải dùng phương thức 

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
3 sau khi thực thi các câu lệnh query làm thay đổi data trong MySQL thì các bạn có thể dùng phương thức
import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
7 để enable disable chế độ auto commit.

Chú ý: Phương thức

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
7 này nằm trong object connection.  Và nếu như bạn làm việc với transaction thì nên tắt chế độ này đi, để không bị ảnh hưởng đến data. Phương thức
import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
7 này nằm trong object connection.  Và nếu như bạn làm việc với transaction thì nên tắt chế độ này đi, để không bị ảnh hưởng đến data.

Cú pháp::

connection.autocommit(flag)

Các tham số và kết quả trả về giống như phương thức

cursor.execute(query, params)
2.:
import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
9 là kiểu
cursor.executemany(query, params)
0 set giá trị autocommit, Mặc định là
cursor.executemany(query, params)
1 - là không ở chế độ auto commit.

VD: Mình sẽ tạo 1 table trong MySQL qua phương thức

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '')

try:
    with connection.cursor() as cursor:
        # create a database
        query = "CREATE DATABASE pymysql"
        print(cursor.execute(query)) # Output: 1

finally:
    # close connection
    connection.close()
2.: Mình sẽ thiết lập autocommit đồng thời insert vào table users dữ liệu test.

import pymysql

# Connect to the database
connection = pymysql.connect('localhost', 'root', '', 'pymysql')
connection.autocommit(True)
try:
    with connection.cursor() as cursor:
        # insert a user
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        print(cursor.execute(sql, ('[email protected]', '123456'))) # output: 1

finally:
    # close connection
    connection.close()