python连接sqlserver_PYTHON连接SQLSERVER实现增删改查等基本操作

import pymssql

import config

server = server1

user = user1

password = password1

conn = pymssql.connect(server, user, password, database1) #获取连接

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.')])

conn.commit()

####删除数据

cursor.execute(

"delete from persons where id=2"

)

conn.commit()

# 查询数据并遍历,结果默认存放到元组之中,要存到字典,需修改cursor = conn.cursor(as_dict=True)

cursor.execute('SELECT * FROM persons WHERE id={0}'.format(3))

row = cursor.fetchone()

while row:

print(row)

row = cursor.fetchone()

####更改数据

cursor.execute(

"update persons set name ='haha' where id=1"

)

conn.commit()

####创建存储过程

cursor.execute("""

CREATE PROCEDURE FindPerson

@name VARCHAR(100)

AS BEGIN

SELECT * FROM persons WHERE name = @name

END

""")

#####调用存储过程

cursor.callproc('FindPerson', ('haha',))

for row in cursor:

print(row)

####执行含聚合函数的语句

cursor.execute('SELECT COUNT(*) FROM persons')

for row in cursor:

print(row[0])

conn.close()#手动关闭连接

#####用with实现自动关闭conn

with pymssql.connect("", "", "", "") 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(row)

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值