python连接数据库 代码示例
时间: 2024-05-14 20:11:20 浏览: 6
Python连接数据库可以使用多个模块,比如pymysql、sqlite3、psycopg2等,以下是一个使用pymysql连接MySQL数据库的示例代码:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='test', charset='utf8')
# 获取游标
cursor = conn.cursor()
# 执行SQL语句
sql = 'SELECT * FROM student'
cursor.execute(sql)
# 获取查询结果
result = cursor.fetchall()
# 输出结果
for row in result:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
```
上述代码中,我们首先通过pymysql模块连接了一个名为test的MySQL数据库,然后获取了一个游标cursor,并执行了一条SELECT语句,最后输出了查询结果。
相关问题
python连接mysql数据库代码示例
好的,以下是一个简单的 Python 连接 MySQL 数据库的代码示例:
```python
import mysql.connector
# 建立数据库连接
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# 创建游标对象
mycursor = mydb.cursor()
# 查询语句
sql = "SELECT * FROM yourtable"
# 执行查询语句
mycursor.execute(sql)
# 获取查询结果
result = mycursor.fetchall()
# 输出查询结果
for row in result:
print(row)
```
请注意,这个示例仅仅是连接到数据库,并查询了数据。如果你要进行其他操作,比如插入、更新或删除数据,需要使用不同的 SQL 语句和方法。同时,你需要替换示例代码中的 `host`、`user`、`password`、`database` 和 `yourtable` 为你自己的实际值。
python连接数据库代码
连接数据库通常需要使用第三方库,Python 中比较流行的库有 `pymysql`、`psycopg2`、`pyodbc` 等。以 `pymysql` 为例,以下是一个连接 MySQL 数据库的示例代码:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(
host='localhost',
user='root',
password='your_password',
database='your_database',
charset='utf8mb4'
)
# 获取游标
cursor = conn.cursor()
# 查询数据
sql = "SELECT * FROM your_table"
cursor.execute(sql)
result = cursor.fetchall()
# 关闭游标和连接
cursor.close()
conn.close()
# 打印结果
print(result)
```
其中,`pymysql.connect()` 方法用于连接数据库,需要指定数据库的连接信息,例如 `host`、`user`、`password`、`database` 等;`conn.cursor()` 方法用于获取游标,通过游标可以执行 SQL 语句,例如 `cursor.execute()` 方法用于执行 SQL 语句;`cursor.fetchall()` 方法用于获取查询结果;最后需要关闭游标和连接,释放资源。