Updated on 2025-10-23 GMT+08:00

connection.autocommit(arg)

Description

Enables or disables the autocommit function for database connections. When PyMySQL is used for connection, the autocommit function is disabled by default. You can use the connection.autocommit(arg) method to enable or disable the function.

Prototype

connection.autocommit(arg)

Parameter

arg: enables or disables the autocommit function for database connections. The value can be True or False.

Return Value

None.

Example

import pymysql
# Create a connection object (non-SSL connection). The character sets of the client and server must be the same. Otherwise, an error is reported.
conn=pymysql.connect(database="database",user="user",password="********",host="localhost",port=port,charset="utf8")
# Create a connection object (SSL connection). The character sets of the client and server must be the same. Otherwise, an error is reported.
conn=pymysql.connect(database="database_name", 
                      user="user", 
                      password="********", 
                      host="IP_address", 
                      port=port,
                      ssl_disabled=False,
                      ssl_ca="file1",
                      ssl_key="file2",
                      ssl_cert="file3"
)
# Note: When using SSL to remotely connect to a database node, you need to use the SHA-256 authentication mode and valid CA root certificates, server public and private keys, and client public and private keys.

assert conn.get_autocommit() == True

# Enable autocommit.
conn.autocommit(False)
assert conn.get_autocommit() == False

# Disable autocommit.
conn.autocommit(True)
assert conn.get_autocommit() == True

# Close a database connection.
conn.close()