1. 程式人生 > >python入門23 pymssql模組(python連線sql server增刪改資料 )

python入門23 pymssql模組(python連線sql server增刪改資料 )

增刪改資料必須connect.commit()才會生效 

回滾函式 connect.rollback()

 

連線資料庫

'''
dinghanhua
sql server增刪改
'''

import pymssql

server = '192.168.1.1'
user = 'user'
password = '111111'
database = 'test'

dbconnect = pymssql.connect(server = server,user = user,password=password,database = database) #
連線到資料庫

 

修改資料

dbcursor.execute("update test_student set name =%s where sno =1",'peter pan')
dbcursor.execute("update test_student set name =%s where sno =2",'silina smith')
dbconnect.commit() #增刪改資料後必須commit

 

刪除資料

dbcursor.execute("delete from test_student  where sno =1",'
peter pan') dbconnect.commit() #增刪改資料後必須commit

 

新增資料

dbcursor.execute("insert into test_teacher values(%d,%s,%s)",(2,'xingxing','111111'))
dbconnect.commit() #增刪改資料後必須commit

 

commit多個

dbcursor.execute("insert into test_teacher values(%d,%s,%s)",(6,'xingxing6','111111'))
dbcursor.execute(
"update test_student set name =%s where sno =2",'peter Panpan') dbconnect.commit() #提交多個

commit之前,遊標再執行select取出的都是未提交的資料

 

rollback()

dbcursor.execute("insert into test_teacher values(%d,%s,%s)",(7,'xingxing7','111111'))
dbconnect.rollback() #回滾
dbcursor.execute("update test_student set name =%s where sno =2",'peter')
dbconnect.commit()  #提交

 

最後關閉連線

dbcursor.close()
dbconnect.close()

 

commit之後資料庫資料已變更,回滾是無效的,必須commit之前回滾。commit之前可以做下判斷。

#避免delete或update未加where語句
with  pymssql.connect(server = server,user = user,password=password,database = database)  as dbconnect:
    with dbconnect.cursor() as dbcursor:
        dbcursor.execute("delete from test_teacher")  #假設忘記加delete

        dbcursor.execute("select count(1) from test_teacher") #查詢下刪除後資料個數
        if dbcursor.fetchone()[0] == 0:
            dbconnect.rollback() #回滾
        else:
            dbconnect.commit()

 

 

with as  替代手工關閉

with  pymssql.connect(server = server,user = user,password=password,database = database)  as dbconnect:
    with dbconnect.cursor(as_dict=True) as dbcursor:

        dbcursor.execute("insert into test_teacher values(%d,%s,%s)",(7,'xingxing7','111111'))
        dbconnect.rollback() #回滾
        dbcursor.execute("update test_student set name =%s where sno =2",'peter234')

        dbcursor.execute("select * from test_student")
        print(dbcursor.fetchall()) #取出的是未提交的資料

        dbconnect.commit()

 

the end!