Python pymysql query a piece of data

The following is a sample code for querying a piece of data using pymysql:

```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 = "SELECT * FROM your_table WHERE id = %s"
        cursor.execute(sql, ('1',))
        
        # 获取查询结果
        result = cursor.fetchone()
        
        # 输出查询结果
        print(result)
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 query statement, where `%s` is a placeholder, which can be replaced with the following parameters to prevent SQL injection attacks. Then use the `cursor.fetchone` method to get the first data of the query result.

Finally, remember to close the database connection to release resources.

Note:
- In actual use, `host`, `user`, `password`, `db` should be changed to actual database information.
- `cursorclass=pymysql.cursors.DictCursor` will return the result in dictionary form, you can directly use the field name to access the data. If this parameter is not set, the result is returned as a tuple.
- `%s` in the query 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.

Guess you like

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