SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
Now we will access and manipulate our database using a python program.
To connect our python script to a MySQL database, we need some special functions,
for which we have a library mysql connector.
Import mysql.connector as sqlcon
we can send our queries from script to the database
Interface Python with MySQL
Step 1 :
To establish the connection to MySQL Database we’ll use connect( ) function.
<connection-object> = sqlcon.connect(host=<host-name>, user=<username>,
passwd=<password> [, database=<database>])
mycon=sqlcon.connect(host='localhost', user='rahul',passwd='ILoveNeha123',database = 'test')
if mycon.is_connected():
print('Successfully Connected to MySQL database')
Connecting DB to object
Step 2 :
When we send our query to the server where it gets executed, the result(what we
asked in query) is sent back to us in one go. But if we want to access the retrieved
data one row at a time, we can’t do it directly. A control structure called database
cursor can be created that gets access of all the records retrieved as per query and
allows us to traverse the result row by row.
cur = mycon.cursor( )
cursor object connector object cursor function
Creating cursor instance
Step 3 :
After making the cursor, we can execute SQL queries using execute( ) function as
per following syntax :
<cursor-object>.execute(<sql query string>)
e.g. cur.execute('select * from student')
*This will store the retrieved records in the cursor object.
Executing SQL query
Step 4 :
Now that records have been retrieved from the database using our Query, we
need to extract the records from cursor or we can say, we need to fetch the data
using fetch() functions.
1. <data>=<cursor>.fetchall() returns all the records retrieved in a tuple form.
2. <data>=<cursor>.fetchone() returns one record as a tuple or list, next time
next record and so on. Returns None if no records.
3. <data>=<cursor>.fetchmany(n) returns ‘n’ records as a tuple, empty tuple if no
records.
4. <var>=<cursor>.rowcount( ) returns number of rows retrieved from the
cursor so far.
Extracting data from cursor
Step 5 :
<connector object>.close( )
e.g. mycon.close( )
Cleaning up the Environment
Step 6 :
At last, we close the connection established.
Parameterized Queries
n=33
cur.execute( 'SELECT * FROM student WHERE marks>n' )
cur.execute( 'SELECT * FROM student WHERE marks>%s'%(33,) )
cur.execute( '---- WHERE marks>%s AND sec='%s' '%(33,'A') )
Parameterized Queries
pass_marks = 33
section = 'A'
query = ' SELECT * FROM student WHERE marks>%s AND sec='%s' '
values = (pass_marks, section)
values2 = (27,'B')
cur.execute(query, values)
cur.execute(query, values2)
'I will score { } out of { }'.format(27,70)
'I will score {0} out of {1}'.format(33,100)
'I will score {marks} out of {total}'.format(total=100, marks=33)
s='SELECT * FROM stu WHERE mrk>{} AND sec='{}''.format(60, ‘A’)
Parameterized Queries
Inserting Queries
By similarly using the execute( ) function, we can insert data in tables.
cur.execute('INSERT INTO student(rollno, name, marks)
VALUES ({}, '{}', {})'.format(141,'Harsh', 99))
mycon.commit( )
cur.execute('UPDATE student SET marks ={}
WHERE marks={}'.format(94,96))
mycon.commit( )
24. SQL .pdf

Weitere ähnliche Inhalte

Ähnlich wie 24. SQL .pdf

Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
cavicav231
 

Ähnlich wie 24. SQL .pdf (20)

Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
The Ring programming language version 1.8 book - Part 34 of 202
The Ring programming language version 1.8 book - Part 34 of 202The Ring programming language version 1.8 book - Part 34 of 202
The Ring programming language version 1.8 book - Part 34 of 202
 
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
Psycopg2 postgres python DDL Operaytions (select , Insert , update, create ta...
 
Interfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptxInterfacing python to mysql (11363255151).pptx
Interfacing python to mysql (11363255151).pptx
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
PythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for DatabasePythonDatabaseAPI -Presentation for Database
PythonDatabaseAPI -Presentation for Database
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
JDBC Connecticity.ppt
JDBC Connecticity.pptJDBC Connecticity.ppt
JDBC Connecticity.ppt
 
The Ring programming language version 1.2 book - Part 18 of 84
The Ring programming language version 1.2 book - Part 18 of 84The Ring programming language version 1.2 book - Part 18 of 84
The Ring programming language version 1.2 book - Part 18 of 84
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
JDBC
JDBCJDBC
JDBC
 
Interface python with sql database.pdf
Interface python with sql database.pdfInterface python with sql database.pdf
Interface python with sql database.pdf
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 
Python session 10
Python session 10Python session 10
Python session 10
 
Jsp project module
Jsp project moduleJsp project module
Jsp project module
 
Python SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite DatabasePython SQite3 database Tutorial | SQlite Database
Python SQite3 database Tutorial | SQlite Database
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

24. SQL .pdf

  • 1.
  • 2. Now we will access and manipulate our database using a python program. To connect our python script to a MySQL database, we need some special functions, for which we have a library mysql connector. Import mysql.connector as sqlcon we can send our queries from script to the database Interface Python with MySQL Step 1 :
  • 3. To establish the connection to MySQL Database we’ll use connect( ) function. <connection-object> = sqlcon.connect(host=<host-name>, user=<username>, passwd=<password> [, database=<database>]) mycon=sqlcon.connect(host='localhost', user='rahul',passwd='ILoveNeha123',database = 'test') if mycon.is_connected(): print('Successfully Connected to MySQL database') Connecting DB to object Step 2 :
  • 4. When we send our query to the server where it gets executed, the result(what we asked in query) is sent back to us in one go. But if we want to access the retrieved data one row at a time, we can’t do it directly. A control structure called database cursor can be created that gets access of all the records retrieved as per query and allows us to traverse the result row by row. cur = mycon.cursor( ) cursor object connector object cursor function Creating cursor instance Step 3 :
  • 5. After making the cursor, we can execute SQL queries using execute( ) function as per following syntax : <cursor-object>.execute(<sql query string>) e.g. cur.execute('select * from student') *This will store the retrieved records in the cursor object. Executing SQL query Step 4 :
  • 6. Now that records have been retrieved from the database using our Query, we need to extract the records from cursor or we can say, we need to fetch the data using fetch() functions. 1. <data>=<cursor>.fetchall() returns all the records retrieved in a tuple form. 2. <data>=<cursor>.fetchone() returns one record as a tuple or list, next time next record and so on. Returns None if no records. 3. <data>=<cursor>.fetchmany(n) returns ‘n’ records as a tuple, empty tuple if no records. 4. <var>=<cursor>.rowcount( ) returns number of rows retrieved from the cursor so far. Extracting data from cursor Step 5 :
  • 7. <connector object>.close( ) e.g. mycon.close( ) Cleaning up the Environment Step 6 : At last, we close the connection established.
  • 8. Parameterized Queries n=33 cur.execute( 'SELECT * FROM student WHERE marks>n' ) cur.execute( 'SELECT * FROM student WHERE marks>%s'%(33,) ) cur.execute( '---- WHERE marks>%s AND sec='%s' '%(33,'A') )
  • 9. Parameterized Queries pass_marks = 33 section = 'A' query = ' SELECT * FROM student WHERE marks>%s AND sec='%s' ' values = (pass_marks, section) values2 = (27,'B') cur.execute(query, values) cur.execute(query, values2)
  • 10. 'I will score { } out of { }'.format(27,70) 'I will score {0} out of {1}'.format(33,100) 'I will score {marks} out of {total}'.format(total=100, marks=33) s='SELECT * FROM stu WHERE mrk>{} AND sec='{}''.format(60, ‘A’) Parameterized Queries
  • 11. Inserting Queries By similarly using the execute( ) function, we can insert data in tables. cur.execute('INSERT INTO student(rollno, name, marks) VALUES ({}, '{}', {})'.format(141,'Harsh', 99)) mycon.commit( ) cur.execute('UPDATE student SET marks ={} WHERE marks={}'.format(94,96)) mycon.commit( )