0% found this document useful (0 votes)
10 views2 pages

2 Database Connection

Uploaded by

ayush231225
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)
10 views2 pages

2 Database Connection

Uploaded by

ayush231225
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

Database Connection

In this section of the tutorial, we will discuss the steps to connect the python application to
the database.

There are the following steps to connect a python application to our database.

1. Import [Link] module


2. Create the connection object.
3. Create the cursor object
4. Execute the query

Creating the connection


To create a connection between the MySQL database and the python application, the
connect() method of [Link] module is used.

Pass the database details like HostName, username, and the database password in the
method call. The method returns the connection object.

The syntax to use the connect() is given below.

1. Connection-Object= [Link](host = <host-name> , user = <username> ,


passwd = <password> )

Consider the following example.

Example
1. import [Link]
2.
3. #Create the connection object
4. myconn = [Link](host = "localhost", user = "root",passwd = "google")
5.
6. #printing the connection object
7. print(myconn)

Output:

<[Link] object at 0x7fb142edd780>

Here, we must notice that we can specify the database name in the connect() method if we
want to connect to a specific database.
Example
1. import [Link]
2.
3. #Create the connection object
4. myconn = [Link](host = "localhost", user = "root",passwd = "google", da
tabase = "mydb")
5.
6. #printing the connection object
7. print(myconn)

Output:

<[Link] object at 0x7ff64aa3d7b8>

Creating a cursor object


The cursor object can be defined as an abstraction specified in the Python DB-API 2.0. It
facilitates us to have multiple separate working environments through the same connection
to the database. We can create the cursor object by calling the 'cursor' function of the
connection object. The cursor object is an important aspect of executing queries to the
databases.

The syntax to create the cursor object is given below.

1. <my_cur> = [Link]()
Example
1. import [Link]
2. #Create the connection object
3. myconn = [Link](host = "localhost", user = "root",passwd = "google", da
tabase = "mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = [Link]()
10.
11. print(cur)

Output:

<[Link] object at 0x7faa17a15748>


MySQLCursor: (Nothing executed yet)

You might also like