import mysql.connector
my_connect = mysql.connector.connect(
host="localhost",
user="userid",
passwd="password",
database="database_name"
)
####### end of connection ####
my_conn = my_connect.cursor()
import mysql.connector
try:
my_connect = mysql.connector.connect(
host="localhost",
user="root",
passwd="test",
database="my_tutorial"
)
except mysql.connector.Error as my_error:
print(my_error.msg) # Error message
print(my_error) # With error number
####### end of connection ####
my_conn = my_connect.cursor()
####### Showing records #####
my_conn.execute("SELECT * FROM student") # SQL to execute
my_result = my_conn.fetchall()
for row in my_result:
print(row)
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:password@localhost/database_name")
If you are getting this error. ( for recent drivers ) from sqlalchemy import create_engine, text
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/db_name").connect()
r_set = my_conn.execute(text("SELECT * FROM student"))
for row in r_set:
print(row)
We will be using the connection variable my_conn
in our scripts here. r_set=my_conn.execute("SHOW TABLES");
for row in r_set:
print(row)
r_set=my_conn.execute(text("SELECT * FROM student"));
for row in r_set:
print(row)
from sqlalchemy import create_engine
my_conn = create_engine("sqlite:///my_db.db")
u_id
:User id of MySQL database pw
: Password for user idloclhost
: Address of MySQL server database
: Database of MySQL to connect
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
try:
my_conn =create_engine("mysql+mysqldb://u_id:pw@localhost/my_tutorial")
my_conn.connect() # error is generated at this stage
except SQLAlchemyError as e:
#print(e)
error = str(e.__dict__['orig'])
print(error)
## connection is over ####
try:
query="SELECT * FROM student1 LIMIT 0,2"
r_set=my_conn.execute(query)
for row in r_set:
print(row)
print('Data displayed ..')
except SQLAlchemyError as e:
#print(e)
error = str(e.__dict__['orig'])
print(error)
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.