How to connect MySQL Database in Python?

 Python is one of the famous programing languages and we can use any type of database in python 
 

To use MySQL driver in your project you must install MYSQL library because unlike PHP PYTHON only supports SQLITE. There are following some of packages that you can easily use in your project.
 

1- Download and install "MySQL Connector" using the following command.

      pip install mysql-connector-python

	import mysql.connector

	
	db = mysql.connector.connect(
		  	host="localhost",
		  	user="root",
		  	password=""
	)

	
	con = db.cursor(dictionary=True)
	
	sql = """
			SELECT id FROM user
			"""
	con.execute(sql)
	
	# Python convert query to comma separated list
	userIdList = ','.join([ str(i['id']) for i in con.fetchall()])
	
	print(userIdList)

 

2- Using MySQLdb python package and install it using following command 

     pip install MySQL-python

import MySQLdb

db = MySQLdb.connect(host="localhost",    
                     user="root",         
                     passwd="",  
                     db="users")        


con= db.cursor()

con.execute("SELECT * FROM users")

#How to convert query to comma separated list in python
userIdList = ','.join([ str(i['id']) for i in con.fetchall()])
	
print(userIdList)

   


Tags:

Share:

Related posts