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
3cnx = mysql.connector.connect(user='scott', password='password',
4 host='127.0.0.1',
5 database='employees')
6cnx.close()
1import mysql.connector
2mydb = mysql.connector.connect(
3 host="localhost",
4 user="yourusername",
5 password="yourpassword",
6 port = 8888, #for Mamp users
7 database='whatever db you want'
8)
9print(mydb)
1
2C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install
3 mysql-connector-python
4
1#!/usr/bin/python3
2
3import pymysql
4
5# Open database connection
6db = pymysql.connect("localhost","testuser","test123","TESTDB" )
7
8# prepare a cursor object using cursor() method
9cursor = db.cursor()
10
11# Drop table if it already exist using execute() method.
12cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
13
14# Create table as per requirement
15sql = """CREATE TABLE EMPLOYEE (
16 FIRST_NAME CHAR(20) NOT NULL,
17 LAST_NAME CHAR(20),
18 AGE INT,
19 SEX CHAR(1),
20 INCOME FLOAT )"""
21
22cursor.execute(sql)
23
24# disconnect from server
25db.close()