Python SQL Server sort the result














































Python SQL Server sort the result



Python SQL Server sort the result

For sorting the result in SQL Server, you have to use ORDER BY clause. Using ORDER BY clause you can sort the result in many ways. For more details, you may prefer Python SQL Server ORDER BY.


Here is the python3 source code to sort the results of selected data

 # Below Code snippet is to sort the result selected

import pyodbc

server = 'Mypc' 

username = 'sa' 

password = 'Windows1'

new_database = 'cpp_db'

#Connecting to MS SQL Server database cpp_db

connection = None

try:

    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';Database='+new_database+';UID='+username+';PWD='+ password)

    print('Connected to SQL Server Database Successfully')

except:

    print('Connection failed to SQL Server Database')


if connection is not None:

    connection.autocommit = True

    

cur = connection.cursor()  

# Drop table if already exist.

cur.execute("DROP TABLE IF EXISTS python_sql_programmer")


# Creating a new table named as 'python_sql_programmer' and inserting data

cur.execute("CREATE TABLE python_sql_programmer (id integer, name varchar(40), rating integer)")

data=[(1,'Bob', 8), 

(2,'John', 7), 

(3, 'Alex', 4), 

(4, 'Scott', 5)]


for i in data:

    cur.execute("INSERT INTO python_sql_programmer (id, name, rating) VALUES{}".format(i))


## Sorting of selected data using ORDER BY. 

cur.execute("SELECT * from python_sql_programmer ORDER BY name ASC;")

data=cur.fetchall()

print('Selected record from table is:')

for i in data:

    print(i)


# After all operation is done close the database connection and cursor

connection.commit()

connection.close()

print('Done') 

Output:

Here, we sort the result according to the name.




Comments