最近用到,範例程式碼如後:
在Python3.x 中raw_input() 和input() 進行了整合,去除了raw_input( ),僅保留了input( )函數,其接收任意任性輸入,將所有輸入默認為字符串處理,並返回字符串類型。
# coding=utf-8 __auther__ = 'xianbao' import sqlite3 # 開啟資料庫 def opendata(): conn = sqlite3.connect("test.db") cur = conn.execute("""create table if not exists userTB (ID integer primary key, IP CHAR(50))""") return cur, conn # 查詢全部的資訊 def showalldata(): print("-------------------處理後後的資料-------------------") hel = opendata() cur = hel[1].cursor() cur.execute("select * from userTB") res = cur.fetchall() for line in res: for h in line: print(h) print() cur.close() # 輸入資訊 def into(): userID = str(input("請輸入使用者ID:")) userIP = str(input("請輸入使用者IP:")) return userID, userIP # (新增) 往資料庫中新增內容 def adddata(): welcome = """-------------------歡迎使用新增資料功能---------------------""" print(welcome) person = into() hel = opendata() hel[1].execute("insert into userTB(ID, IP)values (?,?)", (person[0], person[1])) hel[1].commit() print("-----------------恭喜你資料,新增成功----------------") showalldata() hel[1].close() # (刪除)刪除資料庫中的內容 def deldata(): welcome = "------------------歡迎您使用刪除資料庫功能------------------" print(welcome) delchoice = input("請輸入您想要刪除使用者ID:") hel = opendata() # 返回遊標conn hel[1].execute("delete from userTB where ID ="+delchoice) hel[1].commit() print("-----------------恭喜你資料,刪除成功----------------") showalldata() hel[1].close() # (修改)修改資料的內容 def alter(): welcome = "--------------------歡迎你使用修改資料庫功能-----------------" print(welcome) changechoice = input("請輸入你想要修改的使用者ID:") hel = opendata() person = into() hel[1].execute("update userTB set ID=?, IP= ? where id="+changechoice, (person[0], person[1])) hel[1].commit() showalldata() hel[1].close() # 查詢資料 def searchdata(): welcome = "--------------------歡迎你使用查詢資料庫功能-----------------" print(welcome) choice = str(input("請輸入你要查詢的使用者ID:")) hel = opendata() cur = hel[1].cursor() cur.execute("select * from userTB where ID="+choice) hel[1].commit() row = cur.fetchone() id1 = str(row[0]) ip1 = str(row[1]) print("-------------------恭喜你,你要查詢的資料如下---------------------") print("您查詢的資料ID是%s" % id1) print("您查詢的資料IP是%s" % ip1) cur.close() hel[1].close() # 是否繼續 def contnue1(a): choice = input("是否繼續?(y or n):") if choice == 'y': a = 1 else: a = 0 return a if __name__ == "__main__": flag = 1 while flag: welcome = "---------歡迎使用資料庫通訊錄---------" print(welcome) choiceshow = """ 請選擇您的進一步選擇: (a)往資料庫裡面新增內容 (d)刪除資料庫中內容 (m)修改書庫的內容 (q)查詢資料的內容 (s)顯示所有資料內容 選擇您想要的進行的操作: """ choice = input(choiceshow) if choice == "a": adddata() contnue1(flag) elif choice == "d": deldata() contnue1(flag) elif choice == "m": alter() contnue1(flag) elif choice == "q": searchdata() contnue1(flag) elif choice == "s": showalldata() contnue1(flag) else: print("你輸入錯誤,請重新輸入")
沒有留言:
張貼留言