python连接数据库——create_engine和conn.cursor
2017-03-14 18:44
645 查看
python操作数据库的方法:
一种是导入sqlalchemy包,另一种是导入psycopg2包。
具体用法如下(此处以postgre数据库举例)
第一种:
# 导入包 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)
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) #增量入库
第二种方法,与jdbc使用极为相似
# 导入包 import psycopg2# 初始化
conn = psycopg2.connect(database = database, user = username, password = passwd, host = host, port = port)
cursor = conn.cursor()
# 执行sql
cursor.execute(sql, values) # 与jdbc的prepareStatement极为类似,执行的是一个具体的sql语句。
cursor也能调存储过程,并且获取返回值。
相关文章推荐
- Python数据库操作、Python DB API、数据库连接对象connection、数据库游标对象cursor
- python之cursor() — 数据库连接操作
- python实践3:cursor() — 数据库连接操作
- cursor() — 数据库连接操作 python
- python实践3:cursor() — 数据库连接操作
- python数据库连接操作---cursor()
- python实践3:cursor() — 数据库连接操作
- python 使用pymssql 连接MSSQL数据库(带端口)
- python 使用pymssql 连接MSSQL数据库(带端口)
- python插入记录后取得主键id的方法(cursor.lastrowid和conn.insert_id())
- python访问PostgreSQL数据库之连接库Psycopg2
- python中cursor操作数据库
- python mysqldb连接数据库
- Create Your Own Search Engine with Python 用python创建你自己的搜索引擎(二)
- Python连接数据库代码结构
- python--连接数据库篇
- 一般情况下asp可以正常运行,但只要连接数据库就提示,Microsoft JET Database Engine 错误
- Windows下Python3.1 连接数据库的办法
- SQLServer_Conn连接数据库
- 学习python 第三季:编写简单简单连接数据库并执行查询操作