How to connect python to mysql database.
Python
Computer Science Engineering
1966
Anaisha
pip
command:
pip install mysql-connector-python
mysql.connector
module into your Python code:
import mysql.connector
Create a connection object to the MySQL database. You will need to pass the following information to the connect()
method:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="my_database"
)
users
table:
cursor = connection.cursor()
cursor.execute("SELECT * FROM users")
for row in cursor:
print(row)
close()
method:
connection.close()
Here is an example of a complete Python code that connects to a MySQL database and executes a SQL query:
import mysql.connector
def main():
connection = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="my_database"
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users")
for row in cursor:
print(row)
connection.close()
if __name__ == "__main__":
main()
This code will connect to the MySQL database my_database
on the local host and select all of the rows from the users
table. The results of the query will be printed to the console.
Sure, here is how to connect Python to MySQL database:
pip install mysql-connector-python
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
username="root",
password="password",
database="mydatabase"
)
cursor = connection.cursor()
users
table.
cursor.execute("SELECT * FRO
results = cursor.fetchall()
cursor.close()
connection.close()
Here is a complete example of connecting Python to MySQL database:
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
username="root",
password="password",
database="mydatabase"
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
for row in results:
print(row)
cursor.close()
connection.close()