9951 explained code solutions for 126 technologies


python-mysqlHow do I connect to a MySQL Lite database using Python?


To connect to a MySQL Lite database using Python, the following steps are needed:

  1. Install the MySQL driver for Python: pip install mysql-connector-python
  2. Import the driver into your code: import mysql.connector
  3. Create a connection object: conn = mysql.connector.connect(host='localhost', database='dbname', user='username', password='password')
  4. Create a cursor object: cursor = conn.cursor()
  5. Execute your SQL query: cursor.execute('SELECT * FROM table_name')
  6. Fetch the results of the query: rows = cursor.fetchall()
  7. Close the connection: conn.close()

Example code

import mysql.connector

conn = mysql.connector.connect(host='localhost', database='dbname', user='username', password='password')

cursor = conn.cursor()

cursor.execute('SELECT * FROM table_name')

rows = cursor.fetchall()

print(rows)

conn.close()

Output example

[('value1', 'value2', 'value3'), ('value4', 'value5', 'value6')]

Helpful links

Edit this code on GitHub