python unit-5
python unit-5
Database Connection
There are the following steps to connect a python application to our
database.
1. Import mysql.connector module
2. Create the connection object.
3. Create the cursor object
4. Execute the query
1. import mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root
",passwd = "google")
5.
6. #printing the connection object
7. print(myconn)
Output:
<mysql.connector.connection.MySQLConnection 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 mysql.connector
2.
3. #Create the connection object
4. myconn = mysql.connector.connect(host = "localhost", user = "root
",passwd = "google", database = "mydb")
5.
6. #printing the connection object
7. print(myconn)
Output:
<mysql.connector.connection.MySQLConnection object at
0x7ff64aa3d7b8>
1. <my_cur> = conn.cursor()
Example
1. import mysql.connector
2. #Create the connection object
3. myconn = mysql.connector.connect(host = "localhost", user = "root
",passwd = "google", database = "mydb")
4.
5. #printing the connection object
6. print(myconn)
7.
8. #creating the cursor object
9. cur = myconn.cursor()
10.
11. print(cur)
Output:
<mysql.connector.connection.MySQLConnection object at
0x7faa17a15748>
MySQLCursor: (Nothing executed yet)
Most of the common databases out there along with working Python
modules and