python操作sql server数据库

pyodbc库

可用于SQL Server数据库的连接,但除此之外,还可用于Oracle,Excel, MySql等,安装Anaconda时默认已安装。

安装:pip install pyodbc

1、连接数据库

1)直接连接数据库和创建一个游标(cursor)(使用过)

coxn=pyodbc.connect(driver="ODBC Driver 13 for SQL Server",server="localhost",user="sa",password="fooww123,",database="testdb")#连接数据库
cursor=coxn.cursor()#获取游标对象

2)使用DSN连接。通常DSN连接并不需要密码,还是需要提供一个PSW的关键字。(未使用过)

 cnxn =pyodbc.connect('DSN=test;PWD=password')
 cursor =cnxn.cursor()
2、操作数据库
所有的SQL语句都用cursor.execute函数运行。
1)查询操作,fetchone获取一行数据
 cursor.execute("select user_id, user_name from users")
 row =cursor.fetchone()
 if row:
  print(row)
2)Row类似于一个元组,但是他们也可以通过字段名进行访问。
 cursor.execute("select user_id, user_name from users")
 row =cursor.fetchone()
 print'name:', row[1# access by column index
 print'name:', row.user_name # or access by name
3)如果所有的行都被检索完,那么fetchone将返回None.
 while 1:
  row= cursor.fetchone()
  ifnot row:
  break
  print'id:', row.user_id
4)使用fetchall函数时,将返回所有行,如果是空行,那么将返回一个空列。(如果有很多行,这样做的话将会占用很多内存。未读取的行将会被压缩存放在数据库引擎中,然后由数据库服务器分批发送。一次只读取你需要的行,将会大大节省内存空间)
 cursor.execute("select user_id, user_name from users")
 rows =cursor.fetchall()
 for row in rows:
  print(row.user_id, row.user_name)
5)数据插入
 cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
 cnxn.commit()
注意调用 cnxn.commit()函数:你必须调用 commit函数,否者你对数据库的所有操作将会失效!当断开连接时,所有悬挂的修改将会被重置。这很容易导致出错,所以你必须记得调用 commit函数。
6)数据修改和删除

    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)

  

猜你喜欢

转载自www.cnblogs.com/crystal1126/p/12681210.html