在Python中获取数据库数据通常需要使用特定的数据库连接库,以下是一些常见数据库及其对应的Python库和连接方式:
MySQL:
使用`pymysql`库连接MySQL数据库。
import pymysql
创建连接
conn = pymysql.connect(
host='192.168.1.110',
user='unickcheng',
password='p123',
database='UNICK',
charset='utf8'
)
创建游标对象
cursor = conn.cursor()
执行SQL查询
cursor.execute('SELECT * FROM your_table_name')
获取查询结果
results = cursor.fetchall()
关闭连接
conn.close()
打印结果
for row in results:
print(row)
SQLite:
使用Python内置的`sqlite3`库连接SQLite数据库。
import sqlite3
创建连接
conn = sqlite3.connect('database.db')
创建游标对象
cursor = conn.cursor()
执行SQL查询
cursor.execute('SELECT * FROM your_table_name')
获取查询结果
results = cursor.fetchall()
关闭连接
conn.close()
打印结果
for row in results:
print(row)
PostgreSQL:
使用`psycopg2`库连接PostgreSQL数据库。
import psycopg2
创建连接
conn = psycopg2.connect(
host='localhost',
port='5432',
database='mydatabase',
user='myuser',
password='mypassword'
)
创建游标对象
cursor = conn.cursor()
执行SQL查询
cursor.execute('SELECT * FROM your_table_name')
获取查询结果
results = cursor.fetchall()
关闭连接
cursor.close()
conn.close()
打印结果
for row in results:
print(row)
确保在使用第三方库之前已经通过`pip`安装了相应的库,例如:
pip install pymysql
pip install psycopg2
对于SQLite,由于其已包含在Python的标准库中,无需额外安装。
如果你需要查看已安装的所有Python库,可以使用以下方法:
使用`help('modules')`查看所有模块的简要描述。
使用`pip list`列出所有已安装的库。
使用`dir()`查看当前命名空间中的所有标识符。