vik-y
1/7/2015 - 8:28 PM

Python MySQLdb example, is helpful in connecting Python with MySQL database

Python MySQLdb example, is helpful in connecting Python with MySQL database

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
'''