lr mysql 增删改查_Python对MySQL进行增删查改
#增刪查改
from Practice_Recode.UserTest.User importUserimportpymysqldefopenDb():globaldb, cursor
db= pymysql.connect("localhost", "root", "test1234", "pythontest", charset='utf8')
cursor=db.cursor()defcloseDb():
db.close()#按照用戶id查詢用戶記錄(輸出相應內容,并返回查到的user對象)
defserarchDb(id):
openDb()
sql= "select * from user where id =" +str(id)
rst=cursor.execute(sql)if rst ==0:#print("查找失敗")
returnNoneelse:#print("查找成功")
data =cursor.fetchone()#print(data)
user1 = User(data[0], data[1], data[2], int(data[3]), data[4], data[5])returnuser1
closeDb()#按照用戶id刪除用戶記錄
defdeleteDb(id):
openDb()
sql= "delete from user where id =" +str(id)
rst=cursor.execute(sql)if rst ==0:print("刪除失敗")else:print("刪除成功")
closeDb()#新增用戶
definsertDb(user1):
openDb()
sql= "insert into user values('%d','%s','%s','%d','%s','%s')" %(
user1.id, user1.username, user1.birth_data, user1.money, user1.father, user1.mother)#"INSERT INTO mytb(title,keywd) VALUES('%s','%s')"%(x,y)
cursor.execute(sql)
db.commit()
closeDb()#更新用戶信息
defupdateDb(user1):
openDb()
sql= "update user set username = '%s', money='%d' where id='%d'" %(user1.username, user1.money, user1.id)#update user set username='C', money=9999 where id=5;
rst =cursor.execute(sql)if rst ==0:print("更新失敗")else:print("更新成功")
closeDb()#測試數據#testuser = serarchDb(5)#testuser.set_username('C')#testuser.set_money(9082)## print(testuser.id, testuser.username, testuser.money, testuser.father, testuser.mother)#updateDb(testuser)
#user1 = User(5, "c", "1111-03-11", 10000, father='A', mother='a')#insertDb(user1)#user2 = User(0, "d", "1111-03-11", 10000, 'A', 'a') # 自增鍵id設置為0,新增時即可實現自增#insertDb(user2)
#user2 = User(1, "A", "1111-03-11", 10000, father=None, mother=None)#user3 = User(2, "a", "1111-03-11", 10000, father=None, mother=None)#user1 = User(3, "B", "1111-03-11", 10000, user2, user3)#user1.dayin()#user1.father.dayin()
總結
以上是生活随笔為你收集整理的lr mysql 增删改查_Python对MySQL进行增删查改的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: logincontroller.java
- 下一篇: java 易变变量_提高java编程质量