python如何读取数据库

原创
ithorizon 7个月前 (10-02) 阅读数 33 #Python

Python中读取数据库的方法

Python中读取数据库的方法有多种,常见的方法包括使用Python内置的sqlite3模块、使用第三方库如MySQLdb或PyMySQL以及使用ORM(对象关系映射)框架如SQLAlchemy或Django ORM。

使用Python内置的sqlite3模块

Python内置的sqlite3模块可以方便地读取SQLite数据库,以下是一个简单的示例代码:

import sqlite3
连接到SQLite数据库
conn = sqlite3.connect('example.db')
创建一个游标对象
cursor = conn.cursor()
执行SQL查询语句
cursor.execute('SELECT * FROM table_name')
获取查询结果
result = cursor.fetchall()
打印结果
for row in result:
    print(row)
关闭数据库连接
conn.close()

使用第三方库如MySQLdb或PyMySQL

使用MySQLdb或PyMySQL库可以方便地读取MySQL数据库,以下是一个使用MySQLdb库的示例代码:

import MySQLdb
连接到MySQL数据库
conn = MySQLdb.connect(host='localhost', user='username', passwd='password', db='database_name')
创建一个游标对象
cursor = conn.cursor()
执行SQL查询语句
cursor.execute('SELECT * FROM table_name')
获取查询结果
result = cursor.fetchall()
打印结果
for row in result:
    print(row)
关闭数据库连接
conn.close()

使用ORM(对象关系映射)框架如SQLAlchemy或Django ORM

使用ORM框架可以方便地读取关系型数据库,如MySQL、PostgreSQL等,以下是一个使用SQLAlchemy的示例代码:

from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData, select, and_
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns 
import pandas_datareader as pdr 
from datetime import datetime 
import pandas as pd 
import numpy as np 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile 
import pandas as pd 
from pandas import ExcelWriter 
from pandas import ExcelFile


热门