Python pymysql inserts a piece of data and returns id

The following is a sample code that uses pymysql to insert a piece of data and return an automatically generated id:

```python
import pymysql

# 连接数据库
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='123456',
    db='your_database',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor
)

try:
    # 创建游标对象
    with conn.cursor() as cursor:
        # 执行插入语句
        sql = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
        values = ('value1', 'value2')
        cursor.execute(sql, values)
        
        # 获取自动生成的id
        inserted_id = cursor.lastrowid
        
        # 提交事务
        conn.commit()
        
        # 输出插入的id
        print(inserted_id)
finally:
    # 关闭数据库连接
    conn.close()
```

In the code, we first connect to the database through the `pymysql.connect` function, and then create a cursor object `cursor`, which can be used to execute SQL statements.

Then use the `cursor.execute` method to execute the insert statement, where `%s` is a placeholder, which can be replaced with the following parameters to prevent SQL injection attacks. `values` is a tuple containing the data values ​​to be inserted.

Then use `cursor.lastrowid` to get the automatically generated id. This method can only get the latest inserted data id after executing the insert statement.

Finally, remember to use `conn.commit()` to commit the transaction so that the data is actually inserted into the database. Close a database connection to free resources.

Note:
- In actual use, `host`, `user`, `password`, `db` should be changed to actual database information.
- `%s` in the insert statement is a placeholder and can be modified according to the actual situation. If there are multiple placeholders, multiple parameters can be passed in, and the order of the parameters must be consistent with the order of the placeholders.
- `column1` and `column2` in the insert statement are the column names to be inserted, which can be modified according to the actual situation.
- After executing the insert statement, be sure to use `conn.commit()` to commit the transaction so that the data is actually inserted into the database. Otherwise the inserted data will not be saved.

Guess you like

Origin blog.csdn.net/qq_26429153/article/details/131766990