1pip3 install mysql-connector-python #Python 3
2pip install mysql-connector-python
1# real nice guide, as well as instalation guide: https://pynative.com/python-mysql-database-connection/
2# pip install mysql-connector-python
3import mysql.connector
4from mysql.connector import Error
5
6try:
7 connection = mysql.connector.connect(host='localhost',
8 database='Electronics',
9 user='pynative',
10 password='pynative@#29')
11 if connection.is_connected():
12 db_Info = connection.get_server_info()
13 print("Connected to MySQL Server version ", db_Info)
14 cursor = connection.cursor()
15 cursor.execute("select database();")
16 record = cursor.fetchone()
17 print("You're connected to database: ", record)
18
19except Error as e:
20 print("Error while connecting to MySQL", e)
21finally:
22 if (connection.is_connected()):
23 cursor.close()
24 connection.close()
25 print("MySQL connection is closed")
1import mysql.connector
2
3mydb = mysql.connector.connect(
4 host="localhost",
5 user="yourusername",
6 password="yourpassword"
7)
8
9print(mydb)
1Press CTRL+C to copy import datetime
2import mysql.connector
3
4cnx = mysql.connector.connect(user='scott', database='employees')
5cursor = cnx.cursor()
6
7query = ("SELECT first_name, last_name, hire_date FROM employees "
8 "WHERE hire_date BETWEEN %s AND %s")
9
10hire_start = datetime.date(1999, 1, 1)
11hire_end = datetime.date(1999, 12, 31)
12
13cursor.execute(query, (hire_start, hire_end))
14
15for (first_name, last_name, hire_date) in cursor:
16 print("{}, {} was hired on {:%d %b %Y}".format(
17 last_name, first_name, hire_date))
18
19cursor.close()
20cnx.close()
1import mysql.connector
2try:
3 connection = mysql.connector.connect(host='localhost',database='dbname',user='root',password='xxxxx')
4 # print(dir(connection))
5 # print(connection.connection_id)
6 if connection.is_connected():
7 db_Info = connection.get_server_info()
8 print("Connected to MySQL Server version ", db_Info)
9 cursor = connection.cursor()
10 cursor.execute("select database();")
11 record = cursor.fetchone()
12 print("You're connected to database: ", record)
13except Error as e:
14 print("except")
15 print("Error while connecting to MySQL", e)
16finally:
17 if (connection.is_connected()):
18 cursor.close()
19 connection.close()
20 print("MySQL connection is closed")