Friday, 10 June 2016

Python: MySQLdb: Create database table

Step 1: Get the connection object.
db = MySQLdb.connect(host, userName, password, database)

Step 2: Get the cursor object
cursor = db.cursor()


Step 3: Execute the CREATE TABLE statement.
sql = """CREATE TABLE employee_info
        (
             id int,
             firstName varchar(30),
             lastName varchar(30),
             salary decimal,
             mailId varchar(30),
             PRIMARY KEY(id)
        )
        """
cursor.execute(sql)

#!/usr/bin/python

# Import MySQLdb module
import MySQLdb

host="localhost"
userName="root"
password="tiger"
database="sample"

# Open connection to a database
db = MySQLdb.connect(host, userName, password, database)

# Get cursor object
cursor = db.cursor()

# Prepare SQL query to create table
sql = """CREATE TABLE employee_info
        (
             id int,
             firstName varchar(30),
             lastName varchar(30),
             salary decimal,
             mailId varchar(30),
             PRIMARY KEY(id)
        )
        """

try:
   # Execute the SQL command
   cursor.execute(sql)

except:
   print("Error: unable to fetch data")

finally:
    # Close the connection to database
    db.close()


Previous                                                 Next                                                 Home

No comments:

Post a Comment