Google News
logo
Python - Interview Questions
How to retrieve data from a table in MySQL database through Python code? Explain.
Import MySQLdb module as : import MySQLdb Establish a connection to the database. db = MySQLdb.connect(“host”=”local host”, “database-user”=”user-name”, “password”=”password”, “database-name”=”database”) Initialize the cursor variable upon the established connection: c1 = db.cursor() Retrieve the information by defining a required query string. s = “Select * from dept” Fetch the data using fetch() methods and print it. data = c1.fetch(s) Close the database connection. db.close()
Advertisement