import pymssql class SqlServer: def __init__(self,host,user,pwd,db): self.host = host #主机名 self.user = user #用户名 self.pwd = pwd #密码 self.db = db #数据库名 def __GetConnect(self): if not self.db: raise(NameError,"没有设置数据库信息") #连接数据库 self.conn = pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset="utf8") cur = self.conn.cursor() if not cur: raise(NameError,"连接数据库失败") else: return cur def ExecQuery(self,sql): #执行查询语句 cur = self.__GetConnect() cur.execute(sql) data = cur.fetchall() #一次获取全部数据 row=cur.fetchone() #一次获取一行数据 rows = cur.fetchmany(10) #获取10行数据 #查询完毕后必须关闭连接 self.conn.close() return data def ExecNonQuery(self,sql): #执行非查询语句 cur = self.__GetConnect() cur.execute(sql) self.conn.commit() self.conn.close() def main(): #使用sa登录,密码为自设sa登录密码 ss = SqlServer(host="localhost",user="sa",pwd="123456",db="mydb") data = ss.ExecQuery("SELECT * FROM Table1") for row in data: print row[0],row[1].encode("utf8") if __name__ == '__main__': main() 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 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对象 复制代码 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', '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 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() import pymssql # server 数据库服务器名称或IP # user 用户名 # password 密码 # database 数据库名称 conn = pymssql.connect(server, user, password, database) 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.')]) # 如果没有指定autocommit属性为True的话就需要调用commit()方法 conn.commit() # 查询操作 cursor.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') row = cursor.fetchone() while row: print("ID=%d, Name=%s" % (row[0], row[1])) row = cursor.fetchone() # 也可以使用for循环来迭代查询结果 # for row in cursor: # print("ID=%d, Name=%s" % (row[0], row[1])) # 关闭连接 conn.close() 注意: 例子中查询操作的参数使用的%s而不是'%s',若参数值是字符串,在执行语句时会自动添加单引号 游标使用注意事项 一个连接一次只能有一个游标的查询处于活跃状态,如下: c1 = conn.cursor() c1.execute('SELECT * FROM persons') c2 = conn.cursor() c2.execute('SELECT * FROM persons WHERE salesrep=%s', 'John Doe') print( "all persons" ) print( c1.fetchall() ) # 显示出的是c2游标查询出来的结果 print( "John Doe" ) print( c2.fetchall() ) # 不会有任何结果 为了避免上述的问题可以使用以下两种方式: 创建多个连接来保证多个查询可以并行执行在不同连接的游标上 使用fetchall方法获取到游标查询结果之后再执行下一个查询, 如下: c1.execute('SELECT ...') c1_list = c1.fetchall() c2.execute('SELECT ...') c2_list = c2.fetchall() 游标返回行为字典变量 上述例子中游标获取的查询结果的每一行为元组类型, 可以通过在创建游标时指定as_dict参数来使游标返回字典变量, 字典中的键为数据表的列名 conn = pymssql.connect(server, user, password, database) 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() 使用with语句(上下文管理器) 可以通过使用with语句来省去显示的调用close方法关闭连接和游标 with pymssql.connect(server, user, password, database) 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'])) 调用存储过程 pymssql 2.0.0以上的版本可以通过cursor.callproc方法来调用存储过程 with pymssql.connect(server, user, password, database) 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 接口自动化的sql验证_python接口自动化测试二十八:连接SQL sever操作
最新推荐文章于 2021-09-22 15:17:03 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)