Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

Python Database Connectivity

Uploaded by

Sagana C. CSE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Python Database Connectivity

Uploaded by

Sagana C. CSE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 12

PYTHON DATABASE

CONNECTIVITY
Database Connection
1.Import mysql.connector module
2.Create the connection object.
3.Create the cursor object
4.Execute the query
Creating the connection

• import mysql.connector to communicate with the MySQL database.


• To create a connection between the MySQL database and the python
application, the connect() method of mysql.connector module is used.
• Pass the database details like HostName, username, and the database
password in the method call, which returns connection object
• Syntax:
• Connection-Object= mysql.connector.connect(host = <host-
name> , user = <username> , passwd = <password> )
Example

import mysql.connector
Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",pas
swd = "google")
#printing the connection object
print(myconn)
Argument Description

Username The username that you use to work with MySQL Server. The default
username for the MySQL database is a root.

Password Password is given by the user at the time of installing the MySQL server. If
you are using root then you won’t need the password.

Host name The server name or Ip address on which MySQL is running. if you are
running on localhost, then you can use localhost or its IP 127.0.0.0

Database name The name of the database to which you want to connect and perform the
operations.
Creating a cursor object
• create the cursor object by calling the 'cursor' function of the connection object.
import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd =
"google", database = "mydb")
#printing the connection object
print(myconn)
#creating the cursor object
= myconn.cursor()
pcurrint(cur)
Creating Tables

import mysql.connector
mydb = mysql.connector.connect(
host = "localhost",
user = "yourusername",
password = "your_password",
database = “mydatabase"
)
cursor = mydb.cursor()
cursor.execute("CREATE TABLE gfg (name VARCHAR(255), user_name VARCHAR(255))")

cur.execute('''CREATE TABLE marks ( StudentID INTEGER


PRIMARY KEY AUTOINCREMENT, name TEXT (20) NOT
NULL);''')
• mysql.connector allows Python programs to access MySQL
databases.
• connect() method of the MySQL Connector class with the arguments
will connect to MySQL and would return a MySQLConnection object
if the connection is established successfully.
• cursor() method of a MySQLConnection object to create a cursor
object to perform various SQL operations.
• execute() methods run the SQL query and return the result.
• cursor.fetchall() or fetchone() or fetchmany() to read query result.
• cursor.clsoe() and connection.clsoe() method to close open
connections after your work completes
Check if Table Exists

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()

mycursor.execute("SHOW TABLES")

for x in mycursor:
print(x)
Insert a Single Row into MySQL table
• INSERT INTO mysql_table (column1, column2, …)
VALUES (value1, value2, …);
Insert multiple rows into MySQL table
using the cursor’s executemany()
• Syntax
• cursor.executemany(operation, seq_of_params)
• INSERT INTO Laptop (Id, Name, Price, Purchase_date)
VALUES (%s, %s, %s, %s)
• records_to_insert = [(4, 'HP Pavilion Power', 1999,
'2019-01-11'), (5, 'MSI WS75 9TL-496', 5799, '2019-
02-27'), (6, 'Microsoft Surface', 2330, '2019-07-
23')]
mport mysql.connector
try:
connection = mysql.connector.connect(host='localhost',
database='Electronics',
user='pynative',
password='pynative@#29')
mySql_insert_query = """INSERT INTO Laptop (Id, Name, Price, Purchase_date)
VALUES (%s, %s, %s, %s) """
records_to_insert = [(4, 'HP Pavilion Power', 1999, '2019-01-11'),
(5, 'MSI WS75 9TL-496', 5799, '2019-02-27'),
(6, 'Microsoft Surface', 2330, '2019-07-23')]
cursor = connection.cursor()
cursor.executemany(mySql_insert_query, records_to_insert)
connection.commit()
print(cursor.rowcount, "Record inserted successfully into Laptop table") #find the number of records inserted
except mysql.connector.Error as error:
print("Failed to insert record into MySQL table {}".format(error))
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

You might also like