1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| import mysql.connector
mydb = mysql.connector.connect( host="localhost", port="3366", user="root", password="123456", database="mydatabase" )
mycursor = mydb.cursor() mycursor.execute("CREATE TABLE test (name VARCHAR(255), address VARCHAR(255))") mycursor.execute("ALTER TABLE test ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY") sql_insert = "INSERT INTO test (name, address) VALUES (%s, %s)" val = [ ("Peter", "Lowstreet 4"), ("Amy", "Apple st 652"), ("Hannah", "Mountain 21"), ("Michael", "Valley 345"), ("Sandy", "Ocean blvd 2"), ("Betty", "Green Grass 1"), ("Richard", "Sky st 331"), ("Susan", "One way 98"), ("Vicky", "Yellow Garden 2"), ("Ben", "Park Lane 38"), ("William", "Central st 954"), ("Chuck", "Main Road 989"), ("Viola", "Sideway 1633") ] mycursor.executemany(sql_insert, val) mydb.commit() print(mycursor.rowcount, "was inserted.") mycursor.execute("SELECT * FROM test") myresult = mycursor.fetchall() for x in myresult: print(x)
print("-----------------------------")
sql_delete = 'DELETE FROM test WHERE address = "Mountain 21"' mycursor.execute(sql_delete) mydb.commit() print(mycursor.rowcount, "record(s) deleted.") mycursor.execute("SELECT * FROM test") myresult = mycursor.fetchall() for x in myresult: print(x)
|