Advertisement
cellsheet

MySQL for python beginners

Jan 24th, 2013
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. import mysql.connector
  2.  
  3. 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
  4. db = database.cursor() #this is assigning a mysql execution object to "db", don't worry about this too much.
  5. 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"
  6. 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!
  7. db.execute("insert into edibles (fruit, vegetables) values(\"pear\", \"salary\");") # we are inserting "pear" into the fruit row, and "salary" into the vegetables row.
  8. db.commit() #you must do this for every insert/delete command.
  9. db.execute("select * from edibles;") #we are getting all the contents of the "edibles" table
  10. edibles = db.fetchall() #This is the command that retrieves the data and stores it into the edibles variable
  11. 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.
  12. edibles = db.fetchall() #meh, whatever
  13. 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"
  14. edible = db.fetchall()
  15. db.execute("delete from edibles where vegetables = \"salary\";") #this deletes the item in the vegetables column if the item is equal to "salary".
  16. db.commit() # don't forget this!
  17. db.close()#at the end, you want to close the cursor.
  18. database.close()# end the connection
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement