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 check the version of MySQL I am using with Python?
- 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 can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How do I format a date in MySQL using Python?
- How can I use Python and MySQL to create a login system?
- How do I connect Python with MySQL using XAMPP?
- How can I use Python and MySQL to generate a PDF?
- How do Python and MySQL compare to MariaDB?
See more codes...