python调用sql数据库_python操作sql server数据库

1)数据修改和删除也是跟上面的操作一样,把SQL语句传递给execute函数。但是我们常常想知道数据修改和删除时,到底影响了多少条记录,这个时候你可以使用cursor.rowcount的返回值。

cursor.execute("delete from products where id <> ?",‘pyodbc‘)

printcursor.rowcount,‘products deleted‘

cnxn.commit()

2)由于execute函数总是返回cursor,所以有时候你也可以看到像这样的语句:(注意rowcount放在最后面)

deleted=cursor.execute("delete from products where id <> ‘pyodbc‘").rowcount

cnxn.commit()

同样要注意调用cnxn.commit()函数

import pyodbc

#封装的一个简单的demo

class MsSql:

def __init__(self,driver,server,user,pwd,db):

self.driver=driver

self.server=server

self.user=user

self.pwd=pwd

self.db=db

def __get_connect(self):

if not self.db:

raise (NameError,"没有设置数据库信息")

self.conn=pyodbc.connect(driver=self.driver,server=self.server,user=self.user,password=self.pwd,database=self.db)#连接数据库

cursor=self.conn.cursor()#使用cursor()方法创建游标对象

if not cursor:

raise (NameError,"连接数据库失败")

else:

return cursor

def exec_query(self,sql):

‘‘‘执行查询语句‘‘‘

cursor=self.__get_connect()

cursor.execute(sql)

res_list=cursor.fetchall()#使用fetchall()获取全部数据

self.conn.close()#查询完毕关闭连接

return res_list

def exec_not_query(self,sql):

‘‘‘执行非查询语句‘‘‘

cursor=self.__get_connect()

cursor.execute(sql)

self.conn.commit()

self.conn.close()

if __name__ == ‘__main__‘:

ms=MsSql(driver="ODBC Driver 13 for SQL Server",server="localhost",user="sa",pwd="fooww123,",db="testdb")

result=ms.exec_query("select id,name from webuser")

for i in result:

print(i)

newsql = "update webuser set name=‘%s‘ where id=1" % u‘aa‘

# print(newsql)

ms.exec_not_query(newsql)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值