- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Database Connection in Python
Before connecting to a MySQL database, make sure of the followings −
- You have created a database TESTDB.
- You have created a table EMPLOYEE in TESTDB.
- This table has fields FIRST_NAME, LAST_NAME, AGE, SEX and INCOME.
- User ID "testuser" and password "test123" are set to access TESTDB.
- Python module MySQLdb is installed properly on your machine.
- You have gone through MySQL tutorial to understand MySQL Basics.
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()
While running this script, it is producing the following result in my Linux machine.
Database version : 5.0.45
If a connection is established with the datasource, then a Connection Object is returned and saved into db for further use, otherwise db is set to None. Next, db object is used to create a cursor object, which in turn is used to execute SQL queries. Finally, before coming out, it ensures that database connection is closed and resources are released.
- Oracle Database Connection in Python
- How to create Database Connection in Perl?
- MySqldb Connection in Python
- Which PHP function is used to disconnect from MySQL database connection?
- Write an example to establish MySQL database connection using PHP script?
- How to determine database type (name) for a given JDBC connection?
- How to work with one database connection object in the entire Java-MySQL application?
- How to establish a connection with the database using the properties file in JDBC?
- Which PHP function is used to establish MySQL database connection using PHP script?
- Disconnecting Database in Python
- Python Unicode Database
- Difference between Connection-oriented and Connection-less Services
- Differences between Connection-oriented and Connection-less Services.
- Creating Database Table in Python
- Database INSERT Operation in Python