Python操作SQL

连接数据库文件
connect = sqlite3.connect('database.db')
获取游标
cursor = connect.cursor()
执行SQL语句
create_student_table = "CREATE TABLE Student (id INTEGER PRIMARY KEY, name TEXT, age INTEGER, score FLOAT)"
cursor.execute(create_student_table)
执行提交的操作
connect.commit()
关闭游标、数据库
cursor.close()
connect.close()
参数化查询
# 导入包
from sqlalchemy import create_engine
import pandas as pd
from string import Template
# 初始化引擎
engine = create_engine('postgresql+psycopg2://' + pg_username + ':' + pg_password + '@' + pg_host + ':' + str(
pg_port) + '/' + pg_database)
##SQL语句
query_sql = """
select * from $arg1
"""
query_sql = Template(query_sql) # template方法
df = pd.read_sql_query(query_sql .substitute(arg1=tablename),engine) # 配合pandas的方法读取数据库值
# 配合pandas的to_sql方法使用十分方便(dataframe对象直接入库)
df.to_sql(table, engine, if_exists='replace', index=False) #覆盖入库
df.to_sql(table, engine, if_exists='append', index=False) #增量入库