How to create Database connection in Python?

Creating a Database

File name : index.py

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="root",
password=""
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

Example

File name : index.py

import mysql.connector

#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "")

#printing the connection object
print(myconn)

Example

File name : index.py

import mysql.connector

#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "", database = "mydb")

#printing the connection object
print(myconn)

Creating a cursor object

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.

File name : index.py

import mysql.connector
#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google", database = "mydb")

#printing the connection object
print(myconn)

#creating the cursor object
cur = myconn.cursor()

print(cur)

Example

File name : index.py

import mysql.connector

#Create the connection object
myconn = mysql.connector.connect(host = "localhost", user = "root",passwd = "google")

#creating the cursor object
cur = myconn.cursor()

try:
#creating a new database
cur.execute("create database PythonDB2")

#getting the list of all the databases which will now include the new database PythonDB
dbs = cur.execute("show databases")

except:
myconn.rollback()

for x in cur:
print(x)

myconn.close()





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here