Last active
August 29, 2015 14:13
-
-
Save vik-y/9df465f72e574b951eb9 to your computer and use it in GitHub Desktop.
Python MySQLdb example, is helpful in connecting Python with MySQL database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import MySQLdb | |
db = MySQLdb.connect( | |
host = 'localhost', | |
user = 'root', | |
passwd = '', | |
db = '', | |
unix_socket = '/opt/lampp/var/mysql/mysql.sock' #This is needed if you are using mysql of xampp installation, else you can remove this | |
) | |
cursor = db.cursor() #cursor is a pointer which you create to make calls to your mysql database | |
cursor.execute("SELECT VERSION()") #here inside the bracket "SELECT VERSION()" is the query which you want to run on the db | |
data = cursor.fetchone() #cursor.fetchone() is used to fetch first row of the result | |
print "Database version: %s " % data #Printing the first row of the result | |
''' | |
More examples | |
''' | |
#Insert Query | |
try: | |
cursor.execute("INSERT INTO table_name (fields) VALUES ('%s')" % (i)) | |
db.commit() | |
except: | |
db.rollback() | |
#SELECT query | |
cursor.execute("SELECT * FROM table_name") | |
result = cursor.fetchall() | |
for values in result: #Printing the first column of all rows of the fetched table | |
print values[1] | |
''' | |
Update and Delete queries can also be written on these lines, if getting confused then look up for the | |
python MySQLdb tutorial on tutorialspoint | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment