Thursday 19 December 2013

Connect to SQL server and retrieve data in python

I have implemented this program which will connect to sql server and retrieve all the database, tables and containing data. we can read all column row data from this program.

for retrieving the SQL server data 1st we have to install one library which is mssql library. Download this library from here Download.

Through this library, it will connect to sql server by SERVER name, username, password and fetch all data like database, tables and tables data.

#!/usr/bin/python
import re
import pymssql
conn = pymssql.connect(host='Ashish', user='Ashish\ashishsql', password='ashish@123')
cur = conn.cursor()
cur.execute("Select * from Sys.databases")
row = cur.fetchall()
print "Database----------Tables------------Data"
for ro in row:
    cur.execute("USE "+ro[0]+" SELECT name FROM sys.tables")
    rew = cur.fetchall()
    for rem in rew:
        if ro[0]!='tempdb':
            cur.execute("USE "+ro[0]+" SELECT * FROM "+rem[0])
            rows = cur.fetchall()
            for row in rows:
                for x in range(0,len(row)):
                    data=str(row[x])
                    print data
conn.close()

This username & password are SQL server credentials
If you want to connect remote SQL server then you have to use below code for it. it will connect through ip.

#!/usr/bin/python
import re
import pymssql
conn = pymssql.connect(server='\\\\192.168.1.18\\SQL Server', host='Ashish', user='Ashish\ashishsql', 

password='ashish@123')
cur = conn.cursor()
cur.execute("Select * from Sys.databases")
row = cur.fetchall()
print "Database----------Tables------------Data"
for ro in row:
    cur.execute("USE "+ro[0]+" SELECT name FROM sys.tables")
    rew = cur.fetchall()
    for rem in rew:
        if ro[0]!='tempdb':
            cur.execute("USE "+ro[0]+" SELECT * FROM "+rem[0])
            rows = cur.fetchall()
            for row in rows:
                for x in range(0,len(row)):
                    data=str(row[x])
                    print data

conn.close()



Thanks guys

No comments:

Post a Comment