CentOS 7
Sponsored Link

SQL Server 2017 : Python で利用する
2017/10/28
 
Python からの SQL Server 利用例です。
[1] Python DB API for ODBC をインストールしておきます。
# EPELからインストール

[root@dlp ~]#
yum --enablerepo=epel -y install pyodbc
[2] テスト用のデータベース接続用ユーザーとデータベースを作成しておきます。
[root@dlp ~]#
sqlcmd -S localhost -U SA

Password:
# ログインユーザー作成
1> create login cent with PASSWORD= N'password';
2> go

# [SampleDB] 作成
1> create database SampleDB;
2> go

1> use SampleDB;
2> go
Changed database context to 'SampleDB'.

# ログインユーザー [cent] と関連付けて DBユーザー作成
1> create user cent for login cent;
2> go

# [cent] にDBオーナーロール付与
1> exec sp_addrolemember 'db_owner', 'cent';
2> go

# テストテーブル作成
1> create table SampleTable (
2> ID int identity(1,1) not null primary key, First_Name NVARCHAR(50), Last_Name NVARCHAR(50)
3> );
4> insert into SampleTable (
5> First_Name, Last_Name) values (N'CentOS', N'Linux'), (N'RedHat', N'Linux'), (N'Fedora', N'Linux'
6> );
7> go
[3] 基本的な利用例です。データベースや接続ユーザーは上記で作成したものを使用します。
[cent@dlp ~]$
vi use_mssql.py
import pyodbc

server = '127.0.0.1'
database = 'SampleDB'
username = 'cent'
password = 'password'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server}; \
    SERVER='+server+'; PORT=1443; DATABASE='+database+'; UID='+username+'; PWD='+ password)
cursor = cnxn.cursor()

# SampleTable を Select
print ('\nReading data from SampleTable')
tsql = "select * from SampleTable;"
with cursor.execute(tsql):
    row = cursor.fetchone()
    while row:
        print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]))
        row = cursor.fetchone()

# SampleTable に Insert
print ('\nInserting a new row into SampleTable')
tsql = "insert into SampleTable (First_Name, Last_Name) values (?,?);"
with cursor.execute(tsql,'Ubuntu','Linux'):
    print ('- Successfuly Inserted!')

# 特定の行を Update
print ('\nUpdating Last_Name for Redhat')
tsql = "update SampleTable set Last_Name = ? where First_Name = ?"
with cursor.execute(tsql,'Maipo','Redhat'):
    print ('- Successfuly Updated!')

tsql = "select * from SampleTable;"
with cursor.execute(tsql):
    row = cursor.fetchone()
    while row:
        print (str(row[0]) + " " + str(row[1]) + " " + str(row[2]))
        row = cursor.fetchone()

# 特定の行を Delete
print ('\nDeleting user Ubuntu')
tsql = "delete from SampleTable where First_Name = ?"
with cursor.execute(tsql,'Ubuntu'):
    print ('- Successfuly Deleted!')

[cent@dlp ~]$
python use_mssql.py


Reading data from SampleTable
1 CentOS Linux
2 RedHat Linux
3 Fedora Linux

Inserting a new row into SampleTable
- Successfuly Inserted!

Updating Last_Name for Redhat
- Successfuly Updated!
1 CentOS Linux
2 RedHat Maipo
3 Fedora Linux
5 Ubuntu Linux

Deleting user Ubuntu
- Successfuly Deleted!
 
Tweet