Python中如何使用connect()函数进行数据库连接
发布时间:2024-01-03 01:30:25
在Python中,我们可以使用connect()函数来进行数据库连接。connect()函数通常来自于第三方库,如sqlite3、pymysql、psycopg2等。每个库都有自己不同的connect()函数用于连接不同类型的数据库。
下面是一些示例,展示如何在Python中使用connect()函数进行数据库连接。
1. 使用sqlite3库连接SQLite数据库:
import sqlite3
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
# 创建一个游标对象
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM tablename")
# 获取所有结果
results = cursor.fetchall()
# 输出结果
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
2. 使用pymysql库连接MySQL数据库:
import pymysql
# 连接到MySQL数据库
conn = pymysql.connect(host='localhost',
user='root',
password='password',
db='database_name')
# 创建一个游标对象
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM tablename")
# 获取所有结果
results = cursor.fetchall()
# 输出结果
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
3. 使用psycopg2库连接PostgreSQL数据库:
import psycopg2
# 连接到PostgreSQL数据库
conn = psycopg2.connect(host='localhost',
user='postgres',
password='password',
dbname='database_name')
# 创建一个游标对象
cursor = conn.cursor()
# 执行SQL语句
cursor.execute("SELECT * FROM tablename")
# 获取所有结果
results = cursor.fetchall()
# 输出结果
for row in results:
print(row)
# 关闭游标和连接
cursor.close()
conn.close()
以上是三个常见的示例,分别用于连接SQLite、MySQL和PostgreSQL数据库。在每个示例中,首先使用connect()函数连接到数据库,然后创建一个游标对象来执行SQL语句。执行SQL查询后,可以通过fetchall()方法获取所有结果,并进行相应的处理。最后,记得要关闭游标和连接。
在实际使用中,我们需要根据具体的数据库类型和库的要求来选择合适的connect()函数,并根据需要进行相应的配置,如指定主机、用户、密码、数据库名称等。
