Python ->
Python script for testing connection to ms-sql database

This example shows how to use pyodbc functionality for connecting to ms-sql database, inserting and selecting records from table.
pyodbc link: https://pypi.python.org/pypi/pyodbc

Before executing Python script, you will have to create empty table "py_test" in database "demo" on your SqlServer instance. In this example i use following connection parameters:
server name: HOME\EXP2012SP2
database: demo
login: sa
password: 123456

-- create table in ms-sql db
CREATE TABLE dbo.py_test
(
id INT IDENTITY(1,1) NOT NULL,
name Varchar(50) NULL
);


#!/usr/bin/env python
# -*- coding: utf-8 -*-

# simple ms-sql example using pyodbc module

import pyodbc


def main():

  # main begin

  con = pyodbc.connect('DRIVER={SQL Server};SERVER=HOME\EXP2012SP2;DATABASE=demo;UID=sa;PWD=123456')
  cursor = con.cursor()

  # truncate table
  cursor.execute('TRUNCATE TABLE dbo.py_test;')
  con.commit()
  # insert record
  cursor.execute('INSERT INTO dbo.py_test (name) VALUES(?)',
                 'py test number 1')
  con.commit()

  print ('')
  # exec select
  cursor.execute('SELECT name FROM dbo.py_test')
  rows = cursor.fetchall()
  for row in rows:
    print row.name

  # main end

if __name__ == "__main__": main()




sqlexamples.info