python-mysqlHow do I connect to a MySQL database using Python?
To connect to a MySQL database using Python, the following steps need to be taken:
-
Install the MySQL Connector/Python package. This can be done using
pip install mysql-connector-python
orconda install -c anaconda mysql-connector-python
depending on the environment. -
Create a connection object using the
connect()
method. This requires the hostname, username, password, and database name. For example:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
print(mydb)
# Output: <mysql.connector.connection.MySQLConnection object at 0x7f3c8d7a7a00>
- Create a cursor object using the
cursor()
method. This will allow us to execute SQL statements. For example:
mycursor = mydb.cursor()
- Execute an SQL statement using the
execute()
method. For example:
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# Output:
# ('John', 'Highway 21')
# ('Peter', 'Lowstreet 4')
# ('Amy', 'Apple st 652')
# ('Hannah', 'Mountain 21')
- Close the connection using the
close()
method. For example:
mydb.close()
Helpful links
More of Python Mysql
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use Python to update multiple columns in a MySQL database?
- How can I connect Python and MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
See more codes...