python连接SQLServer数据库

525514222.png


python连接微软的sql server数据库用的第三方模块叫做pymssql

官方文档:http://www.pymssql.org/en/stable/index.html

在官方文档可以看到,pymssql是基于_mssql模块做的封装,是为了遵守python的DBAPI规范接口. 两者关系如下:

python连接SQLServer数据库

一、使用pymssql连接sql server数据库并实现数据库基本操作

官方api: http://www.pymssql.org/en/stable/ref/pymssql.html

import pymssql
server = "127.0.0.1" # 连接服务器地址
user = "username"   # 连接帐号
password = "123456"  # 连接密码
conn = pymssql.connect(server, user, password, "连接默认数据库名称") #获取连接
cursor = conn.cursor() # 获取光标

创建表

cursor.execute("""
IF OBJECT_ID('persons', 'U') IS NOT NULL

DROP TABLE persons

CREATE 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()

关闭连接

conn.close()

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

二、调用存储过程:

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']))
python连接SQLServer数据库

三、使用_mssql连接sql server数据库

官方api: http://www.pymssql.org/en/stable/ref/_mssql.html

import _mssql

创建连接

conn = _mssql.connect(server='SQL01', user='user', password='password', \

database='mydatabase')

创建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', 'John Doe')
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 id IN (%s)', (tuple(xrange(4)),))

关闭连接

conn.close()

Last modification:January 9th, 2019 at 11:52 am
If you think my article is useful to you, please feel free to appreciate

Leave a Comment