python 链接mysql
时间: 2024-06-21 10:01:19 浏览: 5
Python链接MySQL通常使用的是名为`mysql-connector-python`或`pymysql`的库。这两个库都是Python中非常流行的用来操作MySQL数据库的工具。以下是使用这两个库的基本步骤:
1. **安装mysql-connector-python**:
```
pip install mysql-connector-python
```
2. **安装pymysql**:
```
pip install pymysql
```
3. **连接到MySQL** (以`mysql-connector-python`为例):
```python
import mysql.connector
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='localhost',
database='your_database')
```
或者使用pymysql:
```python
import pymysql
cnx = pymysql.connect(host='localhost',
user='your_username',
password='your_password',
db='your_database')
```
4. **创建游标(Cursor)执行SQL查询**:
```python
cursor = cnx.cursor()
query = "SELECT * FROM your_table"
cursor.execute(query)
```
5. **处理结果**:
```python
for (row) in cursor:
print(row)
cursor.close()
cnx.close()
```
6. **执行SQL命令(如插入、更新、删除)**:
```python
insert_query = "INSERT INTO your_table (column1, column2) VALUES (%s, %s)"
cursor.execute(insert_query, ('value1', 'value2'))
cnx.commit() # 提交事务
```
7. **错误处理**:
```python
try:
# SQL代码
except mysql.connector.Error as err:
print("Something went wrong: {}".format(err))
```
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)