My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
PymssqlExamples  
Example scripts using pymssql module.
en, ko
Updated Apr 16, 2011 by dam...@gmail.com

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. Note the as_dict argument.

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()

Calling stored procedures

As of pymssql 2.0.0 stored procedures can be called using the rpc interface of db-lib.

import pymssql
conn = pymssql.connect(host='SQL01', user='user', password='password', database='mydatabase', as_dict=True)
cur = conn.cursor()

cur.callproc('findPerson', ('John Doe',))
for row in cur:
    print "ID=%d, Name=%s" % (row['id'], row['name'])

conn.close()
Comment by mbroad...@gmail.com, Apr 27, 2010

Thank you for examples and building the interface.

Comment by carlos.l...@gmail.com, Jul 15, 2010
I'll try it. Thanks for the work.
Comment by wayne.da...@gmail.com, Nov 27, 2010

Thank you very much

Comment by jagana...@gmail.com, Mar 4, 2011

When I tried the example I am getting the following erro in Feora14


OperationalError? Traceback (most recent call last)

/home/jaganadhg/Desktop/YahooKDDCup/trunk/<ipython console> in <module>()

/usr/lib/python2.7/site-packages/pymssql.pyc in connect(dsn, user, password, host, database, timeout, login_timeout, trusted, charset, as_dict, max_conn)

605 con = mssql.connect(dbhost, dbuser, dbpasswd, trusted, charset, max_conn=max_conn) 606 except mssql.MssqlDatabaseException?, e:
--> 607 raise OperationalError?, e0?
608 except mssql.MssqlDriverException?, e: 609 raise InterfaceError?, e0?

OperationalError?: DB-Lib error message 20009, severity 9: Unable to connect: Adaptive Server is unavailable or does not exist Net-Lib error during Operation now in progress Error 115 - Operation now in progress How to solve it

Comment by WBSPress...@gmail.com, Mar 29, 2011

The above example for rows as dictionaries has a little bug in it? I think the loop should be: for row in cur.fetch_all():

Otherwise, I cannot get the rows to be dictionaries. This is behavior is from the ubuntu 10.04 universe repo:

# apt-cache show python-pymssql Package: python-pymssql Priority: optional Section: universe/python Installed-Size: 184 Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com> Original-Maintainer: Josselin Mouette <joss@debian.org> Architecture: amd64 Source: pymssql Version: 1.0.2+dfsg-1 Depends: libc6 (>= 2.4), libsybdb5 (>= 0.63), python (<< 2.7), python (>= 2.6), python-support (>= 0.90.0) Filename: pool/universe/p/pymssql/python-pymssql_1.0.2+dfsg-1_amd64.deb Size: 28316 MD5sum: 1e9c36f5abc39058b93965de65017df2 SHA1: b53fae710c2ab612691b1f6f26682f6ed21fba11 SHA256: 4db61b74fbf1b4422fcc03a5856f9887775924dcab5bb017eaeb98823a369904 Description: Python database access for MS SQL server and Sybase

This package contains a Python module allowing direct access to Microsoft SQL server and Sybase databases. It is designed for simplicity and performance, and conforms to Python DB-API 2.0. . It also includes a Nagios plugin to check MS SQL servers remotely.
Bugs: https://bugs.launchpad.net/ubuntu/+filebug Origin: Ubuntu

Comment by WBSPress...@gmail.com, Mar 29, 2011

oops. I meant: for row in cur.fetchall():

Comment by darrell....@gmail.com, Apr 21, 2011

I tried the following code with no success and no error message:

import pymssql

conn = pymssql.connect(host=db_host, user=db_user, password=db_password, database=db, as_dict=True) cur = conn.cursor() cur.execute("SELECT VolumeID,Title FROM Volumes WHERE Title like %s", pattern)
for row in cur:
print "VolumeID=%s, Title=%s" % (row['volumeid'], row['title'])
conn.close()

The connect seems to work fine and the execute returns no error but it also doesn't print anything. If I connect to the database with an SQL client and run the same query statement I get 74 rows back. If I look at the cur variable in my debugger (Eclipse with PyDev?) cur.rowcount is -1.

Additionally, if I use tsql from the command line and run the query it works fine and my freedts.log file shows the tsql activity but nothing from my python. I've tried converting it to mssql as well with no errors but no data either.

Mac OS X 10.6.7 Python 2.7 pymssql 1.0.2

Anyone have any ideas?

Comment by jriveram...@gmail.com, May 6, 2011

Has anyone an example of create_engine with sqlalchemy using pymssql? I don't find one

Comment by jriveram...@gmail.com, May 6, 2011

I have found it!! just changes mssql: ---> mssql+pymsql: in the create_engine

Comment by muithimw...@gmail.com, Oct 25, 2011

is there a way of telling that conn.commit() executed successfully e.g. return a value for success? i want after an insert of values into another database table msssql? then if insert to mssql was successful then i proceed to update another table column in a mysql table.


Sign in to add a comment
Powered by Google Project Hosting