Python操作SQLServer資料庫增刪改查

字母搬运工-Hauk發表於2024-10-09
# coding:utf-8
 
import pymssql
def fn_query(cursor):
    # 查詢
    sql = 'SELECT * from Test'
    cursor.execute(sql)
    row = cursor.fetchone()
    while row:
        print(row)
        row = cursor.fetchone()
 
 
def fn_insert(cursor):
    # 新增
    insertSql = "INSERT INTO Test([PKEY], [SN])VALUES( '{e5df4c99-d4ba-ec11-9c30-005056afba00}', N'11')"
    cursor.execute(insertSql)
 
 
def fn_update(cursor):
    # 更新
    insertSql = "UPDATE Test SET sn='111' WHERE PKEY='E5DF4C99-D4BA-EC11-9C30-005056AFBA00'"
    cursor.execute(insertSql)
 
 
def fn_delete(cursor):
    # 刪除
    insertSql = "DELETE Test WHERE PKEY='E5DF4C99-D4BA-EC11-9C30-005056AFBA00'"
    cursor.execute(insertSql)
 
 
if __name__ == '__main__':
    # 連線資料庫
    conn = pymssql.connect(host='localhost', user='sa',password='sa', database='Test', charset='GBK')
    cursor = conn.cursor()
    conn.autocommit(True)
 
    fn_delete(cursor)
    fn_insert(cursor)
    fn_update(cursor)
    fn_query(cursor)
 
    cursor.close()
    conn.close()

相關文章