Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. # 06/2019
  2. # test mysql connector
  3. # install with: pip3 install mysql-connector
  4.  
  5. import mysql.connector
  6.  
  7. mydb = mysql.connector.connect(
  8. host="localhost",
  9. user="root",
  10. passwd="11111",
  11. database="my_test_database"
  12. )
  13.  
  14. print(mydb)
  15.  
  16. mycursor = mydb.cursor()
  17.  
  18.  
  19. # ---- drop table
  20.  
  21. sql = "DROP TABLE IF EXISTS customers"
  22. mycursor.execute(sql)
  23.  
  24.  
  25. # ---- create table
  26. mycursor.execute("CREATE TABLE `customers` (`name` VARCHAR(255), `address` VARCHAR(255))")
  27.  
  28.  
  29. # ---- insert one
  30.  
  31. sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
  32. val = ("John", "Highway 21")
  33. mycursor.execute(sql, val)
  34. mydb.commit()
  35. print("1 record inserted, ID:", mycursor.lastrowid)
  36.  
  37.  
  38. # ---- insert many
  39.  
  40. sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
  41. val = [
  42. ('Peter', 'Lowstreet 4'),
  43. ('Amy', 'Apple st 652'),
  44. ('Hannah', 'Mountain 21'),
  45. ('Michael', 'Valley 345'),
  46. ('Sandy', 'Ocean blvd 2'),
  47. ('Betty', 'Green Grass 1'),
  48. ('Richard', 'Sky st 331'),
  49. ('Susan', 'One way 98'),
  50. ('Vicky', 'Yellow Garden 2'),
  51. ('Ben', 'Park Lane 38'),
  52. ('William', 'Central st 954'),
  53. ('Chuck', 'Main Road 989'),
  54. ('Viola', 'Sideway 1633')
  55. ]
  56. mycursor.executemany(sql, val)
  57. mydb.commit()
  58. print(mycursor.rowcount, "was inserted.")
  59.  
  60.  
  61. # ---- fetch many
  62.  
  63. mycursor.execute("SELECT * FROM customers")
  64. myresult = mycursor.fetchall()
  65. for x in myresult:
  66. print(x)
  67.  
  68.  
  69. # ---- fetch one
  70.  
  71. mycursor.execute("SELECT * FROM customers LIMIT 1")
  72. myresult = mycursor.fetchone()
  73. print("one fetched: ", myresult)
  74.  
  75.  
  76. # ---- delete
  77.  
  78. sql = "DELETE FROM customers WHERE address = %s"
  79. adr = ("Yellow Garden 2", )
  80. mycursor.execute(sql, adr)
  81. mydb.commit()
  82. print(mycursor.rowcount, "record(s) deleted")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement