0% found this document useful (0 votes)
3 views12 pages

SQL Cheat Sheet

This document is a cheat sheet for accessing databases using Python, specifically focusing on SQLite and Db2. It provides syntax examples for creating connections, executing SQL commands, and retrieving data using methods from the sqlite3 and ibm_db libraries. Additionally, it covers functions from the Pandas library for reading and writing data to SQL databases.

Uploaded by

humairosl25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

SQL Cheat Sheet

This document is a cheat sheet for accessing databases using Python, specifically focusing on SQLite and Db2. It provides syntax examples for creating connections, executing SQL commands, and retrieving data using methods from the sqlite3 and ibm_db libraries. Additionally, it covers functions from the Pandas library for reading and writing data to SQL databases.

Uploaded by

humairosl25
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

SQL Cheat Sheet: Accessing Databases using Python

SQLite

Descriptio
Topic Syntax Example
n

Create a
new
database
and open a
database
connection
to allow
sqlite3 to
work with 1. 1
it.
2. 2
Call sqlite3
.connect() t 1. import sqlite3
connec sqlite3.con
o create a
t() nect() 2. con =
connection
sqlite3.connect("INSTRUC
to the
TOR.db")
database
INSTRUCTO Copied!Wrap Toggled!
R.db in the
current
working
directory,
implicitly
creating it if
it does not
exist.

cursor( con.cursor() To execute 1. 1


) SQL
1. cursor_obj = con.cursor()
statements
and fetch Copied!Wrap Toggled!
results from
SQL
queries, use
a database
cursor.
Call con.cu
rsor() to
create the
Cursor.

The execut
e method
in Python's
SQLite
library
allows to
perform
SQL
commands,
including
retrieving
data from a
table using 1. 1
a query like
1. cursor_obj.execute('''inse
"Select *
execut cursor_obj.e rt into INSTRUCTOR
from
e() xecute() values (1, 'Rav', 'Ahuja',
table_name
'TORONTO', 'CA')''')
." When you
execute this Copied!Wrap Toggled!
command,
the result is
obtained as
a collection
of table
data stored
in an
object,
typically in
the form of
a list of
lists.
1. 1

2. 2

3. 3
The fetchal
l() method 4. 4
in Python
5. 5
retrieves all
the rows 1. statement = '''SELECT *
fetchall cursor_obj.f from the FROM INSTRUCTOR'''
() etchall() result set of
2. cursor_obj.execute(state
a query and
ment)
presents
them as a 3. output_all =
list of cursor_obj.fetchall()
tuples.
4. for row_all in output_all:

5. print(row_all)

Copied!Wrap Toggled!

fetchm cursor_obj.f The fetchm 1. 1


any() etchmany() any() meth
2. 2
od retrieves
the 3. 3
subsequent
4. 4
group of
rows from 5. 5
the result
1. statement = '''SELECT *
set of a
FROM INSTRUCTOR'''
query
rather than 2. cursor_obj.execute(state
just a single ment)
row. To
3. output_many =
fetch a few
cursor_obj.fetchmany(2)
rows from
the table, 4. for row_many in
use output_many:
fetchmany(
5. print(row_many)
numberofro
ws) and
mention
how many
Copied!Wrap Toggled!
rows you
want to
fetch.

read_sql_q
uery() is a
function
provided by
the Pandas
library in
Python, and
it is not
specific to
MySQL. It is 1. 1
a generic
read_s 1. df =
read_sql_qu function
ql_quer pd.read_sql_query("select
ery() used for
y() * from instructor;", conn)
executing
SQL queries Copied!Wrap Toggled!
on various
database
systems,
including
MySQL, and
retrieving
the results
as a Pandas
DataFrame.

shape dataframe.s It provides 1. 1


hape a tuple
1. df.shape
indicating
the shape Copied!Wrap Toggled!
of a
DataFrame
or Series,
represented
as (number
of rows,
number of
columns).

close() con.close() con.close() 1. 1


is a method
1. con.close()
used to
close the Copied!Wrap Toggled!
connection
to a MySQL
database.
When
called, it
terminates
the
connection,
releasing
any
associated
resources
and
ensuring
the
connection
is no longer
active. This
is important
for
managing
database
connections
efficiently
and
preventing
resource
leaks in
your MySQL
database
interactions
.

CREAT CREATE The CREAT 1. 1


E TABLE E
2. 2
TABLE table_name TABLE stat
( column1 ement is 3. 3
datatype used to
4. 4
constraints, define and
column2 create a 5. 5
datatype new table
6. 6
constraints, within a
... ); database. It 1. CREATE TABLE
specifies INTERNATIONAL_STUDEN
the table's T_TEST_SCORES ( <br>
name, the
2. country VARCHAR(50),
structure of
<br>
its columns
(including 3. first_name VARCHAR(50),
data types <br>
and
4. last_name VARCHAR(50),
constraints)
<br>
, and any
additional 5. test_score INT
properties
6. );
such as
indexes. Copied!Wrap Toggled!
This
statement
essentially
sets up the
blueprint
for
organizing
and storing
data in a
structured
format
within the
database.

seaborn.ba
rplot() is a
function in
the Seaborn
Python data
visualizatio
n library
used to
create a bar
plot, also
1. 1
known as a
seaborn.bar
bar chart. It 2. 2
plot(x="x-
is
axis_variabl 1. import seaborn
barplot particularly
e", y="y-
() used to 2. seaborn.barplot(x='Test_
axis_variabl
display the Score',y='Frequency',
e",
relationship data=dataframe)
data=data)
between a
Copied!Wrap Toggled!
categorical
variable
and a
numeric
variable by
showing the
average
value for
each
category.

read_cs df = read_csv() 1. 1
v() pd.read_csv( is a function
2. 2
'file_path.cs in Python's
v') Pandas 1. import pandas
library used
2. df =
for reading
pandas.read_csv('https://
data from a
data.cityofchicago.org/res
Comma-
Separated
Values
(CSV) file
and loading
it into a
Pandas
DataFrame. ource/jcxq-k9xf.csv')
It's a Copied!Wrap Toggled!
common
method for
working
with tabular
data stored
in CSV
format

to_sql() df.to_sql('ta df.to_sql() 1. 1


ble_name', is a method
2. 2
index=False in Pandas, a
) Python data 3. 3
manipulatio
1. import pandas
n library
used to 2. df =
write the pandas.read_csv('https://
contents of data.cityofchicago.org/res
a ource/jcxq-k9xf.csv')
DataFrame
3. df.to_sql("chicago_socioe
to a SQL
conomic_data", con,
database. It
if_exists='replace',
allows to
index=False,method="m
take data
ulti")
from a
DataFrame Copied!Wrap Toggled!
and store it
structurally
within a
SQL
database
table.

read_sql()
is a function
provided by
the Pandas
library in
Python for
executing
SQL queries
and
1. 1
retrieving
the results 2. 2
into a
df = 1. selectQuery = "select *
DataFrame
read_s pd.read_sql( from INSTRUCTOR"
from an
ql() sql_query,
SQL 2. df =
conn)
database. pandas.read_sql(selectQu
It's a ery, conn)
convenient
Copied!Wrap Toggled!
way to
integrate
SQL
database
interactions
into your
data
analysis
workflows.

Db2

Descriptio
Topic Syntax Example
n

connec conn = ibm_db.con 1. 1


t() ibm_db.connect('D nect() is a
2. 2
ATABASE=dbname; Python
HOST=hostname;P function 3. 3
provided by
the ibm_db
library,
which is
used for 4. 4
establishing
a 1. import ibm_db
connection 2. conn =
to an IBM ibm_db.connect('
Db2 or IBM DATABASE=mydb
ORT=port;UID=use
Db2 ;
rname;
Warehouse
PWD=password;', 3. HOST=example.c
database.
'', '') om;PORT=50000;
It's
commonly UID=myuser;
used in 4. PWD=mypasswor
applications d;', '', '')
that need to
interact with Copied!Wrap Toggled!
IBM Db2
databases
from
Python.

server_i ibm_db.server_info ibm_db.ser 1. 1


nfo() () ver_info(con
2. 2
n) is a
Python 3. 3
function
4. 4
provided by
the ibm_db 1. server =
library, ibm_db.server_inf
which is o(conn)
used to
2. print
retrieve
("DBMS_NAME: ",
information
server.DBMS_NAM
about the
E)
IBM Db2
server to 3. print
("DBMS_VER: ",
server.DBMS_VER
)
which you
are 4. print ("DB_NAME:
connected. ",
server.DB_NAME)

Copied!Wrap Toggled!

close() con.close() con.close() 1. 1


is a method
1. con.close()
used to
close the Copied!Wrap Toggled!
connection
to a db2
database.
When
called, it
terminates
the
connection,
releasing
any
associated
resources
and
ensuring the
connection
is no longer
active. This
is important
for
managing
database
connections
efficiently
and
preventing
resource
leaks in your
db2
database
interactions.

ibm_db.exe
c_immediat
e() is a
Python
function
provided by
1. 1
the ibm_db
library, 2. 2
which is
3. 3
used to
execute an 1. # Lets first drop
SQL the table
sql_statement =
statement INSTRUCTOR in
"SQL statement
immediately case it exists from
goes here"
exec_i without the a previous
stmt =
mmedi need to attempt.
ibm_db.exec_imme
ate() prepare or
diate(conn, 2. dropQuery =
bind it. It's
sql_statement) "drop table
commonly
INSTRUCTOR"
used for
executing 3. dropStmt =
SQL ibm_db.exec_imm
statements ediate(conn,
that don't dropQuery)
require
Copied!Wrap Toggled!
input
parameters
or don't
need to be
prepared in
advance.

Author(s)

You might also like