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 connect to MySQL using Python?
- How can I use Yum to install the MySQLdb Python module?
- How can I use Python to retrieve data from MySQL?
- How do I connect to a MySQL database using XAMPP and Python?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
See more codes...