How do I execute multiple SQL statements at once? - Python

0 votes
How do I execute multiple SQL statements at once using python?
Jun 20 in Python by Vedant
258 views

1 answer to this question.

0 votes

You can use sqlite3 module. Have a look at this example:

import sqlite3 

# Connection with the DataBase 

# 'library.db' 

connection = sqlite3.connect("library.db") 

cursor = connection.cursor() 

# SQL piece of code Executed 

# SQL piece of code Executed 

cursor.executescript(""" 

CREATE TABLE people( 

firstname, 

lastname, 

age 

); 

CREATE TABLE book( 

title, 

author, 

published 

); 

INSERT INTO 

book(title, author, published) 

VALUES ( 

'Dan Clarke''s GFG Detective Agency', 

'Sean Simpsons', 

1987 

); 

""") 

sql = """ 

SELECT COUNT(*) FROM book;"""


cursor.execute(sql) 

# The output in fetched and returned 

# as a List by fetchall() 

result = cursor.fetchall() 

print(result) 

sql = """ 

SELECT * FROM book;"""

cursor.execute(sql) 

result = cursor.fetchall() 

print(result) 

# Changes saved into database 

connection.commit() 

# Connection closed(broken) 

# with DataBase 

connection.close() 
answered Jun 20 by Travis

Related Questions In Python

0 votes
2 answers

How do I copy a file in python?

copy a file in python  from shutil ...READ MORE

answered Mar 27 in Python by rajesh
• 1,210 points
58 views
0 votes
1 answer

How do I copy a file in python?

Use the shutil module. copyfile(src, dst) Copy the contents ...READ MORE

answered Jul 31, 2018 in Python by Priyaj
• 56,520 points
34 views
0 votes
1 answer

Writing unit tests in Python: How do I start?

If you're brand new to using unittests, ...READ MORE

answered Sep 18, 2018 in Python by Priyaj
• 56,520 points
37 views
0 votes
2 answers

How do I connect to a MySQL Database in Python?

connect mysql database with python import MySQLdb db = ...READ MORE

answered Mar 28 in Python by rajesh
• 1,210 points
137 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 216 views
+4 votes
6 answers
0 votes
1 answer

How can I use python to execute a curl command?

For sake of simplicity, maybe you should ...READ MORE

answered Oct 11, 2018 in Python by charlie_brown
• 7,720 points
14,064 views
0 votes
1 answer

How do I generate some random numbers with a distribution using Python?

scipy.stats.rv_discrete is what you ned IMHO. You can supply ...READ MORE

answered Oct 31, 2018 in Python by Anirudh
• 2,070 points

edited Dec 14, 2018 by Anirudh 133 views