Interface Python with MySQL-2
Interface Python with MySQL-2
SQL Syntax:
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',)
<connection_object>.commit()
So after inserting new rows in the table same should be done:
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.
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.
cnt=mycur.rowcount
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.
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)
mycur.execute(q)
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,
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()