python对sqlite3进行增删查改的操作

╰+攻爆jí腚メ 2022-12-06 05:44 417阅读 0赞

Python操作sqlite3(增删查改)

  1. import sqlite3
  2. con=sqlite3.connect('G:\sqllite3\demo.db')
  3. cur=con.cursor()
  4. def create_tab():
  5. sql='''create table if not exists lin( pno INTEGER primary key , name VARCHAR not null, age INTEGER ) '''
  6. try:
  7. cur.execute(sql)
  8. print('创建表成功')
  9. except Exception as e:
  10. print(e)
  11. print('创建表失败')
  12. finally:
  13. cur.close()
  14. con.close()
  15. def insert_tab():
  16. sql="insert into lin(name,age) values(?,?)"
  17. try:
  18. cur.execute(sql,['李某',15])
  19. con.commit()
  20. print('插入成功')
  21. except Exception as e:
  22. print(e)
  23. con.rollback()
  24. print("插入失败")
  25. finally:
  26. cur.close()
  27. con.close()
  28. def delete_tab():
  29. sql='delete from lin where pno=?'
  30. try:
  31. cur.execute(sql,(3,))
  32. con.commit()
  33. print('删除成功')
  34. except Exception as e:
  35. print(e)
  36. con.rollback()
  37. print('删除失败')
  38. finally:
  39. cur.close()
  40. con.close()
  41. def update_tab():
  42. sql="update lin set name=? where pno=?"
  43. try:
  44. cur.execute(sql,['赵九',2])
  45. con.commit()
  46. print('修改成功')
  47. except Exception as e:
  48. print(e)
  49. con.rollback()
  50. print('打印失败')
  51. finally:
  52. cur.close()
  53. con.close()
  54. def select_tab():
  55. sql="select * from lin"
  56. try:
  57. cur.execute(sql)
  58. person_all=cur.fetchall()
  59. #遍历出数据
  60. for person in person_all:
  61. print(person)
  62. except Exception as e:
  63. print(e)
  64. con.rollback()
  65. print('查询失败')
  66. finally:
  67. cur.close()
  68. con.close()
  69. def inserts_tab():#插入多条数据
  70. sql="insert into lin (name,age) values(?,?)"
  71. try:
  72. cur.executemany(sql,[('赵一',11),('赵二',12),('赵三',13),('赵四',14)])
  73. con.commit()
  74. print('插入多条记录成功')
  75. except Exception as e:
  76. print(e)
  77. con.commit()
  78. print('插入多条记录失败')
  79. finally:
  80. cur.close()
  81. con.close()
  82. if __name__ == '__main__':
  83. create_tab()#先创建表,这里运行一次,把他注释掉,已经创建好了,不然会报错
  84. #insert_tab()
  85. #inserts_tab()
  86. delete_tab()
  87. #select_tab()
  88. #update_tab()

这是一个简单的操作sqllite3的增删查改操作

发表评论

表情:
评论列表 (有 0 条评论,417人围观)

还没有评论,来说两句吧...

相关阅读