python 连接mysql 代码
时间: 2023-09-04 20:06:45 浏览: 16
好的,下面是 Python 连接 MySQL 的示例代码:
```python
# 导入 MySQLdb 模块
import MySQLdb
# 连接 MySQL 数据库
db = MySQLdb.connect(host="localhost", user="root", password="password", database="test")
# 创建游标对象
cursor = db.cursor()
# 执行 SQL 语句
cursor.execute("SELECT * FROM students")
# 获取结果集
results = cursor.fetchall()
# 输出结果
for row in results:
print(row)
# 关闭游标和数据库连接
cursor.close()
db.close()
```
其中,`host` 是 MySQL 服务器地址,`user` 是连接 MySQL 的用户名,`password` 是连接 MySQL 的密码,`database` 是要连接的数据库名。执行 SQL 语句可以使用 `execute()` 方法,获取结果集可以使用 `fetchall()` 方法。最后,记得关闭游标和数据库连接。
相关问题
python连接mysql代码
好的,以下是Python连接MySQL的代码示例:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 执行SQL查询
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM yourtable")
# 获取查询结果
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
python链接mysql代码
以下是一个简单的Python程序,连接到MySQL数据库并执行查询操作的示例。请注意,您需要先安装MySQL驱动程序(例如PyMySQL)才能运行此代码。
```python
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost', user='root', password='password', database='test')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT * FROM students")
# 使用 fetchall() 方法获取所有数据
data = cursor.fetchall()
# 输出每一行数据
for row in data:
print(row)
# 关闭数据库连接
db.close()
```
相关推荐












