[Python] CRUD in database SQLServer


Description
     This tutorial will help you to make python can connect to database SQLServer and execute some command like CRUD (CREATE, UPDATE, READ, DELETE). the SQLServer library not include in default installation package, so you must download and install manually.     

HowTo
1. Install the latest Python.
2. Download library for SQLServer (Pymssql) from this site
3. After installation successfully, now you use the library. here's sample code for CRUD.


#--------------------------------START HERE-----------------------------------------------------------
import pymssql

conn = pymssql.connect(host='localhost', user='usrnm', password='passwd', Database='mydb')
cur = conn.cursor() 

#CREATE , INSERT , UPDATE, SELECT always use execute command
cur.execute('CREATE TABLE test(id INT, name VARCHAR(100))')
cur.execute("INSERT INTO test(id,name) VALUES('3','mahendra')")
cur.execute("UPDATE test set name='rony' where id='1'")
cur.execute("DELETE from test where id='1'")
conn.commit() # don't forget to commit after manipulating database

#To retrieve data / select you can do this
cur.execute('SELECT * from test')
row = cur.fetchone()

while row:
      #Index column fields in database always from 0
      print (row[0],row[1])
      row = cur.fetchone()

conn.close() #don't forget close connection after all process CRUD complete

Post a Comment

Harap gunakan bahasa yang baik dan sopan, terima kasih