Auto AdSense

Saturday, 13 December 2014

Python Program - Database Connection


Before connecting to a MySQL database make sure followings:
  1. You have created a database TESTDB.
  2. You have created a table EMPLOYEE in TESTDB.
  3. This table is having fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
  4. User ID "testuser" and password "test123" are set to access TESTDB
  5. Python module MySQLdb is installed properly on your machine.
  6. You have gone through MySQL tutorial to understand MySQL Basics.



  • Example:
    Following is the example of connecting with MySQL database "TESTDB"

    #!/usr/bin/python

    import MySQLdb

    # Open database connection
    db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

    # prepare a cursor object using cursor() method
    cursor = db.cursor()

    # execute SQL query using execute() method.
    cursor.execute("SELECT VERSION()")

    # Fetch a single row using fetchone() method.
    data = cursor.fetchone()

    print "Database version : %s " % data

    # disconnect from server
    db.close()

No comments:

Post a Comment