Python MySQL connection

We need to download and install mysql connector for python.
import mysql.connector

my_connect = mysql.connector.connect(
  host="localhost",
  user="userid",
  passwd="password",
  database="database_name"
)
####### end of connection ####
my_cursor = my_connect.cursor()
MySQLCursor class instantiates objects to execute SQL statement. Such Cursor objects interact with MySQL database through MySQL connector.

In above code we have declared my_cursor as cursor object
We will use my_cursor having connection string in our applications.

Python to MySQL connector

With error message using try except

import mysql.connector
try:
    my_connect = mysql.connector.connect(
      host="localhost",
      user="root",
      passwd="test",
      database="my_tutorial1"
    )
except mysql.connector.Error as my_error:
    print(my_error.msg)  #  Error message
    print(my_error)      #  With error number 
####### end of connection ####
my_cursor = my_connect.cursor()
Each time we run the script we will add one record. We will get confirm ( of adding record ) message by reading the rowcount value.

Here is the code to capture error while inserting the record into the table. Here we have added one wrong field ( column ) name for class.

Using mysqlclient

Read on how to install mysqlclient
Connection string is here
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://userid_here:password_here@localhost/db_name")
my_conect = engine.connect()
We will be using the connection variable my_connect in our scripts here. More on Error handling



Collecting Records


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2020 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer