python连接mysql数据库的图书筛选代码
时间: 2024-06-14 17:04:46 浏览: 21
以下是使用Python连接MySQL数据库进行图书筛选的代码示例:
```python
import mysql.connector
# 连接到MySQL数据库
cnx = mysql.connector.connect(user='your_username', password='your_password',
host='your_host', database='your_database')
# 创建游标对象
cursor = cnx.cursor()
# 执行SQL查询语句
query = "SELECT * FROM books WHERE category = 'fiction'"
cursor.execute(query)
# 获取查询结果
results = cursor.fetchall()
# 打印查询结果
for book in results:
print(book)
# 关闭游标和数据库连接
cursor.close()
cnx.close()
```
这段代码首先使用`mysql.connector`模块连接到MySQL数据库,然后创建一个游标对象。接下来,执行一个SQL查询语句,筛选出图书分类为"fiction"的图书。最后,通过循环打印查询结果。最后,关闭游标和数据库连接。
相关问题
python 连接mysql数据库 读取数据代码
可以参考以下代码:
``` python
import pymysql
db = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='database_name')
cursor = db.cursor()
cursor.execute('SELECT * FROM table_name')
data = cursor.fetchall()
for row in data:
print(row)
db.close()
```
其中,host、port、user、password、db分别为数据库的主机名、端口号、用户名、密码和数据库名。table_name为数据表名。执行SELECT语句后,可以使用fetchall()方法获取所有查询结果。最后记得关闭数据库连接。
python连接mysql数据库代码
以下是Python连接MySQL数据库的代码示例:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 执行SQL查询
mycursor.execute("SELECT * FROM customers")
# 获取查询结果
myresult = mycursor.fetchall()
# 输出结果
for x in myresult:
print(x)
```
其中,`host`是数据库服务器的地址,`user`和`password`是登录数据库的用户名和密码,`database`是要连接的数据库名称。`mycursor`是游标对象,用于执行SQL查询和获取查询结果。`execute`方法用于执行SQL查询,`fetchall`方法用于获取查询结果。最后,使用`for`循环输出查询结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)