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 access MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python and MySQL to generate a PDF?
- How can I connect to MySQL using Python?
- How can I connect Python and MySQL?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I insert JSON data into a MySQL database using Python?
- How can I connect Python to a MySQL database?
See more codes...