python連接SQL server實現(xiàn)insert() 和讀取數(shù)據(jù)
發(fā)布日期:2022/9/2 6:42:33 瀏覽量:
首先需要安裝一個package:pymssql
1、數(shù)據(jù)庫連接
import pymssql as py
import pandas as pd
# 連接數(shù)據(jù)庫,創(chuàng)建學生表,進行表查詢,表錄入
server = "DESKTOP-G8THN71"# 連接服務器地址
user = "sa"# 連接帳號
password = "1234"# 連接密碼
conn = py.connect(server, user, password, "student_message") #獲取連接
cursor = conn.cursor() # 獲取光標
2、數(shù)據(jù)庫插入
def insert(Name, studentID, Sex):
count_students = 0
conn = py.connect(server, user, password, "student_message") # 獲取連接
cursor =conn.cursor()
cursor.execute(’ select count(ID) from students’)
for row in cursor:
count_students = row[0]
print(row[0])
cursor.executemany(
"INSERT INTO students VALUES (%d, %s, %d,%s)",
[(count_students+1, Name, studentID, Sex)])
# 你必須調用 commit() 來保持你數(shù)據(jù)的提交如果你沒有將自動提交設置為true
conn.commit()
3、通過某項信息,查詢返回信息
def readName(idnum):
Name = -1
conn = py.connect(server, user, password, "student_message") # 獲取連接
cursor =conn.cursor()
cursor.execute(’ select Name from students where ID=’+str(idnum))
for row in cursor:
if row[0]!=[]:
Name = row[0]
conn.commit()
return Name
馬上咨詢: 如果您有業(yè)務方面的問題或者需求,歡迎您咨詢!我們帶來的不僅僅是技術,還有行業(yè)經驗積累。
QQ: 39764417/308460098 Phone: 13 9800 1 9844 / 135 6887 9550 聯(lián)系人:石先生/雷先生