能在具体一点吗
时间: 2023-12-24 09:06:03 浏览: 34
当然。以下是一个完整的示例代码,包括创建表、插入数据、查询数据等操作:
```python
import pymysql
# 建立数据库连接
conn = pymysql.connect(
host='localhost',
port=3306,
user='root',
password='password',
database='testdb',
charset='utf8mb4'
)
# 获取游标
cursor = conn.cursor()
# 创建表
create_table_sql = """CREATE TABLE IF NOT EXISTS users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
age INT UNSIGNED,
PRIMARY KEY (id)
)"""
cursor.execute(create_table_sql)
# 插入数据
insert_sql = "INSERT INTO users (name, age) VALUES (%s, %s)"
cursor.execute(insert_sql, ('Alice', 20))
cursor.execute(insert_sql, ('Bob', 25))
cursor.execute(insert_sql, ('Charlie', 30))
conn.commit()
# 查询数据
select_sql = "SELECT * FROM users WHERE age > %s"
cursor.execute(select_sql, (25,))
result = cursor.fetchall()
for row in result:
print(row)
# 关闭数据库连接和游标
cursor.close()
conn.close()
```
以上代码实现了以下功能:
1. 建立数据库连接并获取游标;
2. 创建一个名为“users”的表,包含“id”、“name”和“age”三个字段;
3. 向表中插入三条数据;
4. 查询年龄大于25岁的用户,并输出结果;
5. 关闭数据库连接和游标。
请注意,这里使用了参数化查询,可以有效防止SQL注入攻击。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)