Data Base Programming
Data Base Programming
We can connect and run queries for a particular database using Python and without writing raw queries in the
terminal or shell of that particular database, we just need to have that database installed in our system.
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language
(SQL) is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating
and Deleting the data from the databases. SQL commands are case insensitive i.e CREATE and create
signify the same command.
For any application, it is very important to store the database on a server for easy data access.
MySQL Connector/Python enables Python programs to access MySQL databases, using an API that is
compliant with the Python Database API Specification v2.0 (PEP 249). It is written in pure Python and does not
have any dependencies except for the Python Standard Library.
Installing module
This module does not come built-in with Python. To install it type the below command in the terminal.
If any issue is there while installing, one can explicitly specify the module version as follows:
After installing the MySQL Python connector, we need to test it to make sure that it is working correctly and we
are able to connect to the MySQL database server without any issues.
In comparision to storing data in flatfiles, its much easier to store, retrive and modify data in a database. We are
going to learn the
Creating a Database
Create a Table
Before you can start working with MySQL database, you need to start the database server. I am using WAMP
server for this tutorial. You also need to install the latest mysql-connetor for this purpose. use pip install mysql-
connector in the command window to download and install it.
mysql.connector.connect(host='localhost',
user='root',
password="123456")
While working with Python we need to work with databases, they may be of different types like MySQL,
SQLite, NoSQL, etc.
MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it
does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard
library and has no dependencies.
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. There
are various Database servers supported by Python Database such as MySQL
GadFly
mSQL
PostgreSQL
Microsoft,
Informix,
Interbase
Oracle,
Sybase etc.
To connect with MySQL database server from Python, we need to import the mysql.connector interface.
Syntax:
The above program illustrates the creation of MySQL database geeks4geeks in which host-name is
localhost, the username is user and password is gfg.
Let’s suppose we want to create a table in the database, then we need to connect to a database. Below is a
program to create a table in the geeks4geeks database which was created in the above program.
Python: MySQL Create Table
MySQL is a Relational Database Management System (RDBMS) whereas the structured Query Language (SQL)
is the language used for handling the RDBMS using commands i.e Creating, Inserting, Updating and Deleting
the data from the databases. SQL commands are case insensitive i.e CREATE and create signify the same
command.
Installation
Follow the below-mentioned process for installing the dependencies for python MySQL
Navigate to the python script directory using the command prompt. Execute the command
1. connect(): This function is used for establishing a connection with the MySQL server. The following are the
arguments that are used to initiate a connection:
(a) user: User name associated with the MySQL server used
to authenticate the connection
(c) database: Data base in the MySQL for creating the Table
1. cursor(): Cursor is the workspace created in the system memory when the SQL command is executed. This
memory is temporary and the cursor connection is bounded for the entire session/lifetime and the
commands are executed
1. execute(): The execute function takes a SQL query as an argument and executes. A query is an SQL
command which is used to create, insert, retrieve, update, delete etc.
The database is an organization of information structured into multiple tables. Databases are organized in such a
way so that manipulating the data is easy i.e Creating, inserting, updating, and deleting etc.
CREATE DATABASE ;
Example: Consider the below example for creating a database in MySQL(Ex: college)
List of databases:
('college',)
('information_schema',)
('mysql',)
('performance_schema',)
('student',)
('students',)
('sys',)
In [4]: import mysql.connector
If a connection is established with the datasource, then a Connection Object is returned and saved into
db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in
turn is used to execute SQL queries. Finally, before coming out, it ensures that database connection is
closed and resources are released.
Example
Creating a Database
After establishing connection with MySQL, to manipulate data in it you need to connect to a database.
You can connect to an existing database or, create your own.
You would need special privileges to create or to delete a MySQL database. So if you have access to the root
user, you can create any database.
In [5]: import mysql.connector
con = mysql.connector.connect(host = "localhost",
user ="root",
password ="123456")
mycursor = con.cursor()
mycursor.execute("Drop DataBASE IF EXISTS student")
mycursor.execute("CREATE DATABASE student")
mycursor.execute("USE student")
The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the
name of the table and, definition (name and datatype) of each column.
Syntax:
column2 datatype,
columnN datatype,
);
The DESC statement gives you the description of the specified table.
Using this you can verify if the table has been created or not as shown below:
It returns an integer value representing the number of rows effected by the query. Once a database connection is
established, you can create tables by passing the CREATE TABLE query to the execute() method.
2.Create a connection object using the mysql.connector.connect() method, by passing the user name, password,
host (optional default: localhost) and, database (optional) as parameters to it.
3.Create a cursor object by invoking the cursor() method on the connection object created above.
4.Then, execute the CREATE TABLE statement by passing it as a parameter to the execute() method.
In this, need to specify the name of the table, column names, and values (in the same order as column names).
Syntax:
Following is the syntax of the INSERT INTO statement of MySQL. INSERT INTO TABLE_NAME (column1,
column2, column3,...columnN) VALUES (value1, value2, value3,...valueN);
Example:
You can verify the records of the table after insert operation using the SELECT statement as:
It is not mandatory to specify the names of the columns always, if you pass values of a record in the same order
of the columns of the table you can execute the SELECT statement without the column names as follows:
fetchall()---->It fetches all the rows in a result set. If some rows have already been extracted from the result set,
then it retrieves the remaining rows from the result set.
In [ ]:
In [ ]: https://www.youtube.com/watch?v=MhaH7o3lf4E