Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import mysql.connector
- database = mysql.connector.connect(user="root", password="pass", host="local", database="db") # connects to the database "db" as "root" user with "pass" password on "local" host
- db = database.cursor() #this is assigning a mysql execution object to "db", don't worry about this too much.
- db.execute("insert into edibles (fruit) values(\"apple\");") #telling the mysql to execute this which puts the string "apple" into the row "fruit" in the table "edibles"
- database.commit() #this "flushes" the data into the table, not sure why its not automatic. Basically it just gets your data actually in there. This is needed!
- db.execute("insert into edibles (fruit, vegetables) values(\"pear\", \"salary\");") # we are inserting "pear" into the fruit row, and "salary" into the vegetables row.
- db.commit() #you must do this for every insert/delete command.
- db.execute("select * from edibles;") #we are getting all the contents of the "edibles" table
- edibles = db.fetchall() #This is the command that retrieves the data and stores it into the edibles variable
- db.execute("select * from edibles where fruit = \"pear\";") #this asks to get the row where the "pear" string is located. It will also include the other column's data as well.
- edibles = db.fetchall() #meh, whatever
- db.execute("select vegetables from edibles where fruit = \"apple\";") #this gets the item in the vegetables column where the item next to it in the fruit row is equal to "apple"
- edible = db.fetchall()
- db.execute("delete from edibles where vegetables = \"salary\";") #this deletes the item in the vegetables column if the item is equal to "salary".
- db.commit() # don't forget this!
- db.close()#at the end, you want to close the cursor.
- database.close()# end the connection
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement