python连接sql server数据库实现增删改查

1)基本语法
import pymssql server = "187.32.43.13" # 连接服务器地址
user = "root"         # 连接帐号
password = "1234"      # 连接密码
conn = pymssql.connect(server, user, password, "连接默认数据库名称" ) #获取连接
cursor = conn.cursor() # 获取光标

# 创建表
cursor.execute( """IF OBJECT_ID('persons', 'U') IS NOT NULL DROP TABLE personsCREATE TABLE persons ( id INT NOT NULL, name VARCHAR(100), salesrep VARCHAR(100), PRIMARY KEY(id))""" )  

# 插入多行数据
cursor.executemany( "INSERT INTO persons VALUES (%d, %s, %s)" ,
[(1, 'John Smith' , 'John Doe' ),
(2, 'Jane Doe' , 'Joe Dog' ),
(3, 'Mike T.' , 'Sarah H.' )])
# 你必须调用 commit() 来保持你数据的提交如果你没有将自动提交设置为true
conn.commit()
# 查询数据
cursor.execute( 'SELECT * FROM persons WHERE salesrep=%s' , 'John Doe' )

# 遍历数据(存放到元组中) 方式1
row = cursor.fetchone()
while row:
print ( "ID=%d, Name=%s" % (row[0], row[1]))
row = cursor.fetchone()
# 遍历数据(存放到元组中) 方式2
for row in cursor:
print('row = %r' % (row,))


# 遍历数据(存放到字典中)
cursor = conn.cursor(as_dict=True)
cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe')
for row in cursor:
print("ID=%d, Name=%s" % (row['id'], row['name']))
conn.close() # 关闭连接

# 注:在任何时候,在一个连接下,一次正在执行的数据库操作只会出现一个cursor对象

2)同时,如果你可以使用另一种语法:with 来避免手动关闭cursors和connection连接
import pymssql server = "187.32.43.13" # 连接服务器地址
user = "root" # 连接帐号
password = "1234" # 连接密码
with pymssql.connect(server, user, password, "你的连接默认数据库名称" ) as conn:
with conn.cursor(as_dict=True) as cursor: # 数据存放到字典中
cursor.execute( 'SELECT * FROM persons WHERE salesrep=%s' , 'John Doe' )
for row in cursor:
print ( "ID=%d, Name=%s" % (row[ 'id' ], row[ 'name' ]))
3)调用存储过程:
with pymssql.connect(server, user, password, "tempdb" ) as conn:
with conn.cursor(as_dict=True) as cursor:
cursor.execute( """CREATE PROCEDURE FindPerson @name VARCHAR(100) AS BEGIN SELECT * FROM persons WHERE name = @name END """ )
cursor.callproc('FindPerson', ('Jane Doe',))
for row in cursor:
print ( "ID=%d, Name=%s" % (row[ 'id' ], row[ 'name' ]))
2.使用 _mssql连接sql server数据库并实现操作(官方api  http://www.pymssql.org/en/stable/ref/_mssql.html)
1)基本语法:
import _mssql # 创建连接 conn = _mssql.connect(server= 'SQL01' , user= 'user' , password= 'password' , \ database= 'mydatabase' )
print(conn.timeout)
print(conn.login_timeout)
# 创建table conn.execute_non_query( 'CREATE TABLE persons(id INT, name VARCHAR(100))' )
# insert数据 conn.execute_non_query( "INSERT INTO persons VALUES(1, 'John Doe')" )conn.execute_non_query( "INSERT INTO persons VALUES(2, 'Jane Doe')" )
# 查询操作 conn.execute_query( 'SELECT * FROM persons WHERE salesrep=%s' , 'John Doe' ) for row in conn: print "ID=%d, Name=%s" % (row[ 'id' ], row[ 'name' ])
#查询数量count() numemployees = conn.execute_scalar( "SELECT COUNT(*) FROM employees" ) # 查询一条数据 employeedata = conn.execute_row( "SELECT * FROM employees WHERE id=%d" , 13) # 带参数查询的几个例子: conn.execute_query( 'SELECT * FROM empl WHERE id=%d' , 13)conn.execute_query( 'SELECT * FROM empl WHERE name=%s' , 'JohnDoe' )
conn.execute_query( 'SELECT * FROM empl WHERE id IN (%s)' , ((5, 6),))
conn.execute_query( 'SELECT * FROM empl WHERE name LIKE %s' , 'J%' )
conn.execute_query( 'SELECT * FROM empl WHERE name=%(name)s AND city=%(city)s' , \ { 'name' : 'John Doe' , 'city' : 'Nowhere' } )
conn.execute_query( 'SELECT * FROM cust WHERE salesrep=%s AND id IN (%s)' , \ ( 'John Doe' , (1, 2, 3)))
conn.execute_query( 'SELECT * FROM empl WHERE id IN (%s)' , (tuple(xrange(4)),))conn.execute_query( 'SELECT * FROM empl WHERE id IN (%s)' , \ (tuple([3, 5, 7, 11]),)) #关闭连接 conn.close()

附python的具体实现

#!/usr/bin/env python
#coding=utf-8
from __future__ import with_statement
from contextlib import closing
import inspect
import pymssql
import uuid
import datetime
#查询操作
with closing(pymssql.connect(host = 'localhost' ,user = 'sa' ,password = 'pppp' ,database = 'blogs' )) as conn :
   cur = conn.cursor()
   #SELECT 长连接查询操作(逐条方式获取数据)
   sql = "select * from pcontent"
   cur.execute(sql)
   for i in range (cur.rowcount):
     print cur.fetchone()
   #SELECT 短链接查询操作(一次查询将所有数据取出)
   sql = "select * from pcontent"
   cur.execute(sql)
   print cur.fetchall()
   #INSERT
   sql = "INSERT INTO pcontent(title)VAlUES(%s)"
   uuidstr = str (uuid.uuid1())
   cur.execute(sql,(uuidstr,))
   conn.commit()
   print cur._result
   #INSERT 获取IDENTITY(在插入一个值,希望获得主键的时候经常用到,很不优雅的方式)
   sql = "INSERT INTO pcontent(title)VAlUES(%s);SELECT @@IDENTITY"
   uuidstr = str (uuid.uuid1())
   cur.execute(sql,(uuidstr,))
   print "arraysite:" ,cur.arraysize
   print cur._result[ 1 ][ 2 ][ 0 ][ 0 ] #不知道具体的做法,目前暂时这样使用
   conn.commit()
   #Update
   vl = '中国'
   sql = 'update pcontent set title = %s where id=1'
   cur.execute(sql,(vl,))
   conn.commit()
   #参数化查询这个是为了避免SQL攻击的
   sql = "select * from pcontent where id=%d"
   cur.execute(sql,( 1 ,))
   print cur.fetchall()
   # 调用存储过程SP_GetALLContent 无参数
   sql = "Exec SP_GetALLContent"
   cur.execute(sql)
   print cur.fetchall()
   # 调用存储过程SP_GetContentByID 有参数的
   sql = "Exec SP_GetContentByID %d"
   cur.execute(sql,( 3 ,))
   print cur.fetchall()
   #调用存储过程SP_AddContent 有output参数的(很不优雅的方式)
   sql = "DECLARE @ID INT;EXEC SP_AddContent 'ddddd',@ID OUTPUT;SELECT @ID"
   cur.execute(sql)
   print cur._result

你可能感兴趣的:(python)