pymssql — simple MS SQL Python extension module

來源:互聯網
上載者:User

pymssql examples (strict DB-API compliance):

 

import

pymssql

conn

=

pymssql

.

connect

(

host='SQL01'

,

user='user'

,

password='password'

,

database='mydatabase'

)

cur

=

conn

.

cursor

()

cur

.

execute

(

'CREATE TABLE persons(id INT, name VARCHAR(100))'

)

cur

.

executemany

(

"INSERT INTO persons VALUES(%d

,
%s

)"

,

/

    [ (

1, 'John Doe'

)

,

(

2, 'Jane Doe'

) ])

conn

.

commit

()

  # you must call commit() to persist your data
if you don't set autocommit to True

cur

.

execute

(

'SELECT * FROM persons WHERE salesrep=%s

'

, 'John Doe'

)

row

=

cur.

fetchone

()

while

row

:

    print

"ID=

%d

, Name=

%s

"

%

(

row

[

0],

row

[

1])

    row

=

cur.

fetchone

()

# if you call execute() with one argument, you can use % sign as usual

# (it loses its special meaning).

cur

.

execute

(

"SELECT * FROM persons WHERE salesrep LIKE 'J%'"

)

conn

.

close

()

You can also use iterators instead
of while

loop. Iterators are DB-API extensions,
and are available since pymssql 1.0.

 

Rows as dictionaries

Since pymssql 1.0.2 rows can be fetched as dictionaries instead of tuples. This
allows for accessing columns by name instead of index.

import

pymssql

conn

=

pymssql

.

connect

(

host='SQL01'

,

user='user'

,

password='password'

,

database='mydatabase'

, as_dict=True

)

cur

=

conn

.

cursor

()

cur

.

execute

(

'SELECT * FROM persons WHERE salesrep=%s

'

, 'John Doe'

)

for

row in

cur

:

    print

"ID=

%d

, Name=

%s

"

%

(

row

[

'id'

],

row

[

'name'

]

)

conn

.

close

()

:http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.