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:
- Install the MySQL driver for Python:
pip install mysql-connector-python - Import the driver into your code:
import mysql.connector - Create a connection object:
conn = mysql.connector.connect(host='localhost', database='dbname', user='username', password='password') - Create a cursor object:
cursor = conn.cursor() - Execute your SQL query:
cursor.execute('SELECT * FROM table_name') - Fetch the results of the query:
rows = cursor.fetchall() - 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
More of Python Mysql
- How do I access MySQL using Python?
- How can I convert a MySQL query to JSON using Python?
- How do I perform a MySQL health check using Python?
- How can I use Python and MySQL together to perform asynchronous operations?
- How can I use Python to retrieve data from MySQL?
- How can I connect Python to a MySQL database?
- How do I set up a secure SSL connection between Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I install a Python package from PyPI into a MySQL database?
- How can I use Python and MySQL to generate a PDF?
See more codes...