Python操作SQLサーバーデータベース

pyodbcライブラリ

SQL Serverデータベースへの接続に使用できますが、Oracle、Excel、MySqlなどにも使用できます。Anacondaのインストール時にデフォルトでインストールされます。

インストール:pip install pyodbc

1.データベースに接続します

1)データベースに直接接続し、カーソルを作成します(使用済み)

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)行はタプルに似ていますが、フィールド名でアクセスすることもできます。
 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関数は常にカーソルを返すため、次のようなステートメントが表示されることもあります(行カウントは最後に配置されることに注意してください)。

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

cnxn.commit()関数の呼び出しにも注意してください

import pyodbc#
単純なデモ クラス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)データベースに接続cursor = self.conn.cursor()#カーソル()メソッドを使用して、カーソルで ない場合はカーソルオブジェクトを作成 raise(NameError、 "Failed to connect to the database" else : カーソルを返す def exec_query(self、sql): '' 'クエリステートメントの実行' '' cursor = self .__ get_connect() cursor.execute(sql) res_list = cursor.fetchall()#fetchall()を使用してすべてのデータを取得する self.conn.close ()クエリの後接続を閉じるres_list def exec_not_query(self、sql): '' 'クエリ以外のステートメントを実行する' '' cursor = self .__ get_connect() cursor.execute(sql) self.conn.commit() self.conn .close() if if __name__ == ' __main__ ':ms = MsSql(driver = "ODBC Driver 13 for SQL Server"、server = "localhost"、user = "sa"、pwd = "fooww123、"、db = "testdb ") 結果= ms.exec_query("select id、name from webuser ") for i結果: プリント(I) newsql = "アップデートのWebUserセット名= '%s'はID = 1" %u'aa」 #プリント(newsql) ms.exec_not_query(newsql)

  

おすすめ

転載: www.cnblogs.com/crystal1126/p/12681210.html