python调用sql
‘壹’ python 如何使用源生sql语句查询多个参数的情况
#coding:utf-8
#anexample
"""
--theSQLServerstorageprocess:
dropprocereproc_getconflist
go
createprocereproc_getconflist
@customerchar(6)
,@servicekeyvarchar(16)=NULL
,@dt_bgndatetime=NULL
,@dt_enddatetime=NULL
asbegin
selectbillsumidxasidx
fromconf_billsum
where1=1
andsumtypeid=1
andisnull(@customer,customercode)=customercode
andisnull(@servicekey,servicekey)=servicekey
andisnull(@dt_bgn,begintime)<endtime
andbegintime<isnull(@dt_end,endtime)
end
go
"""
importpymssql
conn=pymssql.connect(
host="192.168.70.7",
user='pyquery',
password='Qpery',
database='gb201412',
)
curr=conn.cursor()
curr.execute("execproc_getconflist%s,%s,%s,%s",
('990003',None,None,None))
foridx,incurr:
printidx
curr.close()
conn.close()
‘贰’ 如何使用python对数据库进行操作
你可以访问Python数据库接口及API查看详细的支持数据库列表。不同的数据库你需要下载不同的DB API模块,例如你需要访问Oracle数据库和Mysql数据,你需要下载Oracle和MySQL数据库模块。
DB-API 是一个规范. 它定义了一系列必须的对象和数据库存取方式, 以便为各种各样的底层数据库系统和多种多样的数据库接口程序提供一致的访问接口 。
Python的DB-API,为大多数的数据库实现了接口,使用它连接各数据库后,就可以用相同的方式操作各数据库。
Python DB-API使用流程:
引入 API 模块。
获取与数据库的连接。
执行SQL语句和存储过程。
关闭数据库连接。
什么是MySQLdb?
MySQLdb 是用于Python链接Mysql数据库的接口,它实现了 Python 数据库 API 规范 V2.0,基于 MySQL C API 上建立的。
如何安装MySQLdb?
为了用DB-API编写MySQL脚本,必须确保已经安装了MySQL。复制以下代码,并执行:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import MySQLdb
如果执行后的输出结果如下所示,意味着你没有安装 MySQLdb 模块:
Traceback (most recent call last):
File "test.py", line 3, in <mole>
import MySQLdb
ImportError: No mole named MySQLdb
‘叁’ Python接入不同类型数据库的通用接口方法
日常数据管理工作中,需要处理存储在不同类型数据库系统的数据。对这些数据的管理,常见的是使用Navicat,DBeaver等管理工具。在对大量数据分析时,需要提取到Python/R中进行处理。下面 探索 Python调用MySQL,MongoDB,InfluxDB等多种类型数据库通用连接方法。实现方式是在Python中封装各类数据库接口包。
实现后的效果:1.安全。接口信息封装便于保密管理;2.复用。一次封装,永久复用;3.上手快。方便不熟悉python和数据调用的同学,只会简单的sql即可使用,省时省力。
下面以MySQL,MongoDB,InfluxDB为例定义接口方法,然后把它们封装成1个通用方法。
mysql_get(sql,db):
mongo_get(sql,db):
influx_get(sql,db):
可以看到,以上函数共同调用的参数为sql和db。我们再增加一个参数db_type,将构造一个通用的方法对以上数据库调用。
同理,其他类型的数据库也可以加入到这个通用框架中,包括但不限于各类关系型,键值型,时序型数据库。
‘肆’ 怎么用python导入SQL
访问MYSQL的话使用,MySQLdb模块
import os,sys
import MySQLdb
try:
conn=MySQLdb.connect(host='localhost',user='root',passwd="",db='YOURDB')
except Exception,e:
print e
sys.exit()
cursor=conn.cursor()
sql="insert into address(name,address) values (%s,%s)"
values=(("zhang","being"),("li","beijing"),("wang","beijing"))
try:
cursor.executemany(sql,values)#插入数条数据
except Exception , e:
print e
sql="select * from address"
cursor.execute(sql) #查询
data=cursor.fetchall()
if data:
for x in data:
print x[0],x[1]
cursor.close()#关闭游标
conn.close()#关闭数据库