0% found this document useful (0 votes)
11 views5 pages

Interface Python with MySQL-2

Uploaded by

bagadbilla402
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views5 pages

Interface Python with MySQL-2

Uploaded by

bagadbilla402
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 5

Create a Table in MySQL with Python

Let's create a simple table "student" which has two columns.

SQL Syntax:

CREATE TABLE student (id INT, name VARCHAR(255))

Example:

import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="netcom",
database="school"
)
db_cursor = db_connection.cursor()
#Here creating database table as student'
db_cursor.execute("CREATE TABLE student (id INT, name VARCHAR(255))")
#Get database table'
db_cursor.execute("SHOW TABLES")
for table in db_cursor:
print(table)

Output:

('student',)

Inserting Data/Rows in a Table


db_cursor.execute(" insert into student values('Deepak',21,99.5)")

Making Changes Permanent in the Table:


After executing queries which make changes to the structure or data of a table the database
needs to be informed that these changes are to be made permanent in the table. So after
executing commands like insert, update, delete, alter etc. you need to call commit() function
using connection object:

<connection_object>.commit()
So after inserting new rows in the table same should be done:

db_cursor.execute(" insert into student values('lalit',22,95.5)")


db_connection.commit() # as we have used db_connection to create connection
View records stored:
db_cursor.execute(" Select * from t1")
for x in db_cursor:
print (x)

View One record At a time:


db_cursor.execute(" Select * from t1")
d= db_cursor.fetchone() # will get first record
print("First ",d)
d= db_cursor.fetchone() # will get second record
print("Second ",d)
for x in db_cursor:# will get remaining records
print (x)

The fetchone() function returns one row from resultset and maintains a pointer which is
initialized pointing to the first record. The fetchone() returns the record pointed by this
pointer. When we fetch one record pointer moves to next record, so next fetchone() returns
second record.

View Multiple records At a time:


The fetchmany(n) function returns n number of records from the current position of the
pointer (where n may be any integer value).

The fetchall() function returns all the remaining records form the current pointer position.

The rowcount property always returns how many records have been fetched so far using
any of the fech() functions.

d= db_cursor.fetchone() # Getting first record


print("First Record",d)
cnt= db_cursor.rowcount
print("Number of records fetched",cnt) # gives 1
d= db_cursor.fetchone() # getting second record
cnt= db_cursor.rowcount
print("Number of records fetched",cnt) # gives 2
print("Second Record ",d)
d= db_cursor.fetchmany(2) # getting 2 more
cnt= db_cursor.rowcount
print("Number of records fetched",cnt) # gives 4
for x in d:
print (x)
d= db_cursor.fetchall() # getting rest records

cnt=mycur.rowcount

print("Number of records fetched",cnt)


for x in d:
print (x)

Parameterized Queries:
db_cursor.execute(" Select * from t1 where roll>=19")

The above query will extract records having roll number greater than or equals to 19, but
writing such queries is not a proper way, the values may keep on changing from time to time
or query to query. So we need to pass values or variable to queries as parameters:

N=22
Select * from t1 where roll>N

Such queries are called parameterised queries. For such queries we need to create string of
query that includes values of parameters. There are two methods for doing so, old and new.

Old Style: In this style, string formatting uses general form: f % v


Where f is a template string and v specifies the value(s) to be formatted using the template.
If multiple values are there then v must be a tuple. v must be prefixed with %.

db_cursor.execute(" Select * from t1 where roll>=%s" %(19,))


#or
q= " Select * from t1 where roll>=%s" %(19,) # creating string
db_cursor.execute(q) # passing string
#or using variable
n=19 # using variable
mycur.execute(" Select * from t1 where roll>=%s" %(n))
#or
q=" Select * from t1 where roll>=%s" %(n) # creating string
mycur.execute(q) # passing string
#or getting input and passing
n=input("Enter range of roll number greater than ")# getting input
q="Select* from t1 where roll>=%s"%(n)#creating string with input
mycur.execute(q) #passing string
#or using multiple arguments
n=input("Enter range of roll number greater than ")
n1=input("Enter range of roll number less than ")
q=" Select * from t1 where roll>=%s and roll <%s" %(n,n1)
mycur.execute(q)

New Style: This style of creating SQL query string uses format() method.
template.format(value1, value2….)
Where template is a string containing mixture of one or more format codes { } embedded in
text. The format method uses the arguments (values) to substitute each format code.
q=”select * from t1 where roll>{} and roll<{}”.format(5, 21)
mycur.execute(q)
#or getting input and passing
n=input("Enter range of roll number greater than ")
n1=input("Enter range of roll number less than ")
q=”select * from t1 where roll>{} and roll<{}”.format(n, n1)
mycur.execute(q)

Performing Insert and Update Queries:


Insert and update operations now can be made either by writing simple queries or by
creating SQL query strings using above methods. For passing strings in template remember
to enclose { } in quotes ‘{ }’
#Inserting data using format
mycur.execute("insert into t1
values('{}',{},{})".format("Aayush",9,96))
q="insert into t1 values('{}',{},{})".format("Shankar",32,90)
mycur.execute(q)
name=input("Enter Name of Student ")
roll=input("Enter Roll Number of Student ")
marks=input("Enter Marks of Student ")
q="insert into t1 values('{}',{},{})".format(name,roll,marks)
mycur.execute(q)

Likewise update operations can be made on existing data:


#Updating/ Editing Records

mycur.execute("Update t1 set roll=2 where name='Ajay'")

q="Update t1 set roll={} where name='{}'".format(2,"Ajay")


mycur.execute(q)

name=input("Enter Name of Student ")

roll=input("Enter Roll Number of Student ")

q="Update t1 set roll={} where name='{}'".format(roll,name)

mycur.execute(q)

ALTER table in MySQL with Python

Alter command is used for modification of Table structure in SQL. Here we will
alter Student table and add a primary key to the id field.

SQL Syntax,

ALTER TABLE student MODIFY id INT PRIMARY KEY

Example,

import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="netcom",
database="school"
)
db_cursor = db_connection.cursor()
#Here we modify existing column id
db_cursor.execute("ALTER TABLE student MODIFY id INT PRIMARY KEY")
DO NOT Forget to call commit() after performing these commands.
Clean Up The Environment:
After you are through with all the processing, in this final step, you need to close the
connection established.
<connection_object>.close()
We established the connection through connection object db_ connection, so write:
db_connection.close()

You might also like