connect to mysql in python

To connect to MySQL in Python, you can use the mysql-connector-python module. First, you need to install it using pip:

main.py
pip install mysql-connector-python
35 chars
2 lines

Then, you can establish a connection to the database using the connect() method of the mysql.connector module. Here's an example:

main.py
import mysql.connector

# establish connection
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  password="yourpassword",
  database="yourdatabase"
)

# create a cursor
mycursor = mydb.cursor()

# execute a query
mycursor.execute("SELECT * FROM yourtable")

# fetch the results
myresult = mycursor.fetchall()

# print the results
for x in myresult:
  print(x)
387 chars
23 lines

In the above example, replace localhost, yourusername, yourpassword, yourdatabase, and yourtable with the appropriate values for your MySQL server.

gistlibby LogSnag