Advertisement
Guest User

mysql_alaa

a guest
Mar 31st, 2018
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. import mysql.connector
  2. from mysql.connector import errorcode
  3. conn = mysql.connector.connect(
  4. user='root',
  5. password='Alaa123123123123123Najmi',
  6. host='127.0.0.1',
  7. database='aywm')
  8.  
  9.  
  10. def create_connection(db_file):
  11. try:
  12. conn = mysql.connector.connect(db_file)
  13. return conn
  14. except errorcode as e:
  15. print(e)
  16. return None
  17.  
  18. def create_table(conn,table,column):
  19. cursor = conn.cursor()
  20. query = "CREATE TABLE IF NOT EXISTS {} ({}) ".format(table, column)
  21. print(query)
  22. try:
  23. cursor.execute(query)
  24. except Exception as e:
  25. print("Something went wrong, Details: {}".format(e))
  26. else:
  27. conn.commit()
  28. print("A Table created successfully")
  29.  
  30. def select_data(conn,column, table, condition=None, fetchall=False):
  31. cursor = conn.cursor()
  32. query = "SELECT {} FROM {} ".format(column, table)
  33. if condition is not None:
  34. query += "WHERE {}".format(condition)
  35. print(query)
  36. try:
  37. cursor.execute(query)
  38. except Exception as e:
  39. print("Something went wrong, Details: {}".format(e))
  40. else:
  41. if fetchall:
  42. result = cursor.fetchall()
  43. return result
  44. else:
  45. result = cursor.fetchone()
  46. return result
  47.  
  48. def insert_date(conn,table, column, value):
  49. cursor = conn.cursor()
  50. query = "INSERT INTO {} ({}) VALUES ({}) ".format(table, column, value)
  51. print(query)
  52. try:
  53. cursor.execute(query)
  54. except Exception as e:
  55. print("Something went wrong, Details: {}".format(e))
  56. else:
  57. conn.commit()
  58. print("A row has been inserted successfully")
  59.  
  60. def update_data(conn,table,column, condition=None):
  61. cursor = conn.cursor()
  62. query = 'UPDATE {} SET {} ' .format(table,column)
  63. if condition is not None:
  64. query+='WHERE {}'.format(condition)
  65. print(query)
  66. try:
  67. cursor.execute(query)
  68. except Exception as e:
  69. print("Something went wrong, Details: {}".format(e))
  70. else:
  71. conn.commit()
  72. def delete_data(conn,table, condition):
  73. cursor = conn.cursor()
  74. query = 'DELETE FROM {} WHERE {}'.format(table, condition)
  75. print(query)
  76. try:
  77. cursor.execute(query)
  78. except Exception as e:
  79. print("Something went wrong, Details: {}".format(e))
  80. else:
  81. conn.commit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement