Advertisement
DrAungWinHtut

db.py

Feb 20th, 2023
1,311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. import pymysql
  2.  
  3. try:
  4.     con = pymysql.connect(
  5.         host='localhost',
  6.         port=3306,
  7.         user='root',
  8.         password='',
  9.         db='test'
  10.     )
  11. except pymysql.err.OperationalError as e:
  12.     print('cant connect database : error code is ', e)
  13.  
  14. cursor = con.cursor()
  15.  
  16. # Define the SQL query
  17. table = 'student_table'
  18. sql = "INSERT INTO " + table + " (id,name, age) VALUES (%s,%s, %s)"
  19.  
  20. # Define the data to be inserted
  21. data = (9, 'tester', 25)
  22.  
  23. # Execute the SQL query
  24. try:
  25.     cursor.execute(sql, data)
  26.     con.commit()
  27.     print("Data inserted successfully")
  28. except pymysql.Error as e:
  29.     con.rollback()
  30.     print("Error inserting data:", e)
  31.  
  32.  
  33. try:
  34.     cursor.execute('select * from student_table')
  35. except pymysql.err.ProgrammingError as e:
  36.     print('Cannot execute query : error code is ', e)
  37.  
  38. results = cursor.fetchall()  # read answer
  39.  
  40. for row in results:
  41.     print(row)
  42.  
  43.  
  44. # Define the SQL query
  45. table = 'student_table'
  46. sql = "update " + table + " set name=%s where id=%s"
  47.  
  48. # Define the data to be inserted
  49. data = ('dog', 3)
  50.  
  51. # Execute the SQL query
  52. try:
  53.     cursor.execute(sql, data)
  54.     con.commit()
  55.     print("Data inserted successfully")
  56. except pymysql.Error as e:
  57.     con.rollback()
  58.     print("Error inserting data:", e)
  59.  
  60.  
  61. try:
  62.     cursor.execute('select * from student_table')
  63. except pymysql.err.ProgrammingError as e:
  64.     print('Cannot execute query : error code is ', e)
  65.  
  66. results = cursor.fetchall()  # read answer
  67.  
  68. for row in results:
  69.     print(row)
  70.  
  71.  
  72. # Define the SQL query
  73. table = 'student_table'
  74. sql = "delete from " + table + " where id=%s"
  75.  
  76. # Define the data to be inserted
  77. data = (10)
  78.  
  79. # Execute the SQL query
  80. try:
  81.     cursor.execute(sql, data)
  82.     con.commit()
  83.     print("Data inserted successfully")
  84. except pymysql.Error as e:
  85.     con.rollback()
  86.     print("Error inserting data:", e)
  87.  
  88.  
  89. try:
  90.     cursor.execute('select * from student_table')
  91. except pymysql.err.ProgrammingError as e:
  92.     print('Cannot execute query : error code is ', e)
  93.  
  94. results = cursor.fetchall()  # read answer
  95.  
  96. for row in results:
  97.     if (row[0] == 7):
  98.         print(row)
  99.  
  100. cursor.close()
  101. con.close()
  102.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement