python mysql连接 代码
时间: 2023-09-01 15:13:55 浏览: 53
在 Python 中连接 MySQL 数据库可以使用 `mysql-connector-python` 模块,以下是一个连接 MySQL 数据库的示例代码:
```python
import mysql.connector
# 连接数据库
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)
# 查询数据
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
```
以上代码中,`mysql.connector.connect()` 方法用于连接 MySQL 数据库,需要传入主机名、用户名、密码和数据库名等参数。连接成功后,可以使用 `cursor()` 方法创建游标对象,然后使用 `execute()` 方法执行 SQL 语句,并使用 `fetchall()` 方法获取所有结果。最后,使用 `for` 循环遍历结果并输出。
相关问题
python 连接mysql 代码
好的,下面是 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)
```