python连接mysql并写入数据pymysql
时间: 2024-11-16 21:20:31 浏览: 23
在Python中,可以使用`pymysql`库来连接MySQL数据库,并执行SQL操作,包括插入数据。以下是基本步骤:
1. **安装pymysql**:
首先需要确保已安装了`pymysql`。如果没有安装,可以使用pip进行安装:
```
pip install pymysql
```
2. **连接到MySQL**:
```python
import pymysql
# 创建连接
connection = pymysql.connect(
host='your_host', # 数据库地址
user='your_username', # 用户名
password='your_password', # 密码
database='your_database' # 数据库名称
)
# 使用with语句自动关闭连接,防止资源泄露
with connection.cursor() as cursor:
# 执行SQL(例如插入数据)
sql = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
values = ('value1', 'value2') # 插入的数据
cursor.execute(sql, values)
connection.commit() # 提交事务
```
3. **插入数据示例**:
```python
table_name = 'your_table'
column1 = 'column1_value'
column2 = 'column2_value'
try:
cursor.execute(f"INSERT INTO {table_name} ({', '.join([column1, column2])}) VALUES (%s, %s)", (column1_value, column2_value))
print("Data inserted successfully")
except Exception as e:
print(f"Error: {str(e)}")
# 关闭游标和连接
cursor.close()
connection.close()
```
4. **注意安全**:
- 避免直接将用户输入拼接到SQL查询中,以防SQL注入攻击。使用参数化查询或预处理语句。
阅读全文
相关推荐


















