Python – Save data in SQL Server on Ubuntu into a file No.95

How to save the results of select statement into a file after connecting to SQL Server on Ubuntu through pyodbc using python is shown in this blog.

▼1. Saving data in SQL Server on Ubuntu into a file

Based on the previous blog using Java as below, pyhon code is shown to save the results of select statement into a file.

Java – Put SQL Server select results into a csv file No.70


▼2. Prerequisites

How to build an environment using Python is shown below.

Python – How to connect to SQL Server on Ubuntu No.92


▼3. Developing Python code to save the results of select query in SQL Server into a file

3-1. Creating Python code

Cursor.fetchone() method is used to save results of select statement into a file.

import time
import pyodbc
import random
import datetime

server = 'localhost'
database = 'testdb'
username = 'sa'
password = 'yourpassword'
driver= '{ODBC Driver 17 for SQL Server}'
success = False
retryc = 0
max_retries = 3

while not success and retryc < max_retries:
    try:
        # create random number
        num = random.randint(100, 10000000)

        cnxn = pyodbc.connect('DRIVER='+driver+';SERVER='+server+',1433;DATABASE='+database+';UID='+username+';PWD='+ password+';',autocommit=False,Timeout=1,Trusted_Connection='no',Encrypt='no')
        cursor0 = cnxn.cursor()
        cursor0.execute("insert into sampledb.dbo.sampletb values ("+ str(num) + ","+ str(num) + ")")
        cursor0.commit()

        cursor = cnxn.cursor()
        cursor.execute("SELECT * FROM sampledb.dbo.sampletb")
        row = cursor.fetchone()
        
        # save the results each line to a file
        with open('/home/xxx/results.txt', 'w') as f:
            while row:
                f.write(str(row[0]) + " " + str(row[1]) + "\n")
                row = cursor.fetchone()
  
        success = True
    except pyodbc.Error as ex:
        retryc += 1
        print("Current Timestamps:" + str(datetime.datetime.now()) + "retry count: " + str(retryc))
        print("==========================")
        print("Error: " + str(ex))
        print("==========================")
        time.sleep(3)

    finally:
        cursor.close()

3-2. Results of this code

“results.txt” is created by running above the code.

Records 1,2,3 in c1 column are inserted previously. the random number 3790247 is generated by the code.

# results.txt
1 1
2 2
3 3
10 10
3790247 3790247

▼4. Reference

  1. Java – Put SQL Server select results into a csv file No.70
  2. Python – How to connect to SQL Server on Ubuntu No.92
  3. cursor.fetchone() https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchone.html

That’s all. have a nice day ahead !!!

Leave a Reply

Your email address will not be published. Required fields are marked *