python使用pymysql链接
时间: 2023-10-24 19:19:53 浏览: 38
连接 MySQL 数据库需要使用 Python 中的 pymysql 模块。下面是一个简单的连接 MySQL 数据库的示例代码:
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host="localhost", user="root", password="password", database="testdb")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data)
# 关闭数据库连接
db.close()
```
在上述代码中,我们首先使用 `pymysql.connect()` 方法连接到 MySQL 数据库,指定了所需的主机地址、用户名、密码和数据库名称。然后,我们使用 `cursor()` 方法创建一个游标对象 `cursor`,使用 `execute()` 方法执行 SQL 查询,使用 `fetchone()` 方法获取查询结果,最后关闭数据库连接。
相关问题
python用pymysql链接数据库mysql
您可以使用`pymysql`库来连接MySQL数据库。以下是一个简单的示例代码:
```python
import pymysql
# 建立数据库连接
conn = pymysql.connect(
host='localhost', # 数据库主机地址
port=3306, # 数据库端口号,默认为3306
user='root', # 数据库用户名
password='password', # 数据库密码
db='mydatabase' # 要连接的数据库名
)
# 创建游标对象
cursor = conn.cursor()
# 执行SQL查询
sql = "SELECT * FROM mytable"
cursor.execute(sql)
# 获取查询结果
results = cursor.fetchall()
for row in results:
print(row)
# 关闭游标和数据库连接
cursor.close()
conn.close()
```
请确保您已经安装了`pymysql`库(可以使用`pip install pymysql`命令进行安装)。在代码中,您需要根据实际情况修改`host`、`port`、`user`、`password`和`db`等参数,以正确连接到您的MySQL数据库。然后,使用游标对象执行SQL查询,并通过`fetchall()`方法获取查询结果。最后,记得关闭游标和数据库连接。
希望对您有所帮助!如有任何问题,请随时提问。
Python pymysql 链接数据库后,使用fetchall 打印结果中文出现乱码
出现乱码的原因是数据库和 Python 之间的编码不一致。可以尝试以下两种方法解决:
1. 在建立数据库连接时设置编码
```python
import pymysql
db = pymysql.connect(host='localhost', user='root', password='password', database='test', charset='utf8')
cursor = db.cursor()
cursor.execute('SELECT * FROM table')
result = cursor.fetchall()
print(result)
```
2. 在执行查询语句后设置编码
```python
import pymysql
db = pymysql.connect(host='localhost', user='root', password='password', database='test')
cursor = db.cursor()
cursor.execute('SET NAMES utf8mb4')
cursor.execute('SELECT * FROM table')
result = cursor.fetchall()
print(result)
```
这样就可以避免中文乱码的问题了。