Python operation sql server database

pyodbc library

It can be used to connect to the SQL Server database, but it can also be used for Oracle, Excel, MySql, etc. It is installed by default when installing Anaconda.

Installation: pip install pyodbc

1. Connect to the database

1) Directly connect to the database and create a cursor (used)

coxn = pyodbc.connect (driver = "ODBC Driver 13 for SQL Server", server = "localhost", user = "sa", password = "fooww123,", database = "testdb") # Connect to the databasecursor 
= coxn.cursor () #Get cursor object

2) Use DSN connection. Usually DSN connection does not require a password, or you need to provide a PSW keyword. (Unused)

 cnxn =pyodbc.connect('DSN=test;PWD=password')
 cursor =cnxn.cursor()
2. Operate the database
All SQL statements are executed with cursor.execute function.
1) Query operation, fetchone gets a row of data
 cursor.execute("select user_id, user_name from users")
 row =cursor.fetchone()
 if row:
  print(row)
2) Row is similar to a tuple, but they can also be accessed by field names.
 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) If all the rows have been retrieved, then fetchone will return None.
 while 1:
  row= cursor.fetchone()
  ifnot row:
  break
  print'id:', row.user_id
4) When using the fetchall function, all rows will be returned, if it is a blank row, then an empty column will be returned. (If there are many rows, doing so will take up a lot of memory. Unread rows will be compressed and stored in the database engine, and then sent by the database server in batches. Only read the rows you need at a time, will greatly save Memory space)
 cursor.execute("select user_id, user_name from users")
 rows =cursor.fetchall()
 for row in rows:
  print(row.user_id, row.user_name)
5) Data insertion
 cursor.execute("insert into products(id, name) values ('pyodbc', 'awesome library')")
 cnxn.commit()
Note that calling cnxn.commit() function: you must call commit the function, whether the person you will fail all operations of the database! When disconnected, all suspended modifications will be reset. This can easily lead to mistakes, so you have to remember to call commit the function.
6) Data modification and deletion

    1) Data modification and deletion is the same as the above operation, passing SQL statements to the executefunction. But we often want to know how many records are affected by data modification and deletion, and cursor.rowcountthe return value you can use at this time .

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

  printcursor.rowcount, 'products deleted'
  cnxn.commit()

    2) Since the executefunction always returns cursor, sometimes you can also see statements like this: (note that rowcount is placed at the end)

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

Also pay attention to calling the cnxn.commit()function

import pyodbc #A 
simple 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, "Database information not set") self.conn = pyodbc.connect (driver = self.driver, server = self.server, user = self. user, password = self.pwd, database = self.db) #Connect to the database cursor = self.conn.cursor () # Use the cursor () method to create a cursor object if not cursor: raise (NameError, "Failed to connect to the database" else : return cursor def exec_query (self, sql): '' 'Execute query statement' '' cursor = self .__ get_connect () cursor.execute (sql) res_list = cursor.fetchall () # Use fetchall () to get all data self.conn.close () #Close the connection after query return res_list def exec_not_query (self, sql): '' 'Execute non-query statement' '' 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")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)

  

Guess you like

Origin www.cnblogs.com/crystal1126/p/12681210.html