How do I make a database connection? (Instance parsing)

Source: Internet
Author: User
In this article, let's take a look at Python database connectionof knowledge, some friends may have just come into contact with the programming language of Python, not particularly in this regard, in the next article will bring you to learn about Database ConnectionRelated knowledge.

Database connection

Learn about the things you need to know before you decide:

1. You have created the database TESTDB.

2. In the TestDB database, you have created table EMPLOYEE

The 3.EMPLOYEE fields are first_name, last_name, age, SEX, and INCOME.

4. Connect to the database TestDB use the user name "TestUser", the password is "test123", you can set your own or directly use the root user name and its password, MySQL database user authorization please use the GRANT command.

5. The Python mysqldb module is already installed on your machine.

Database Connection Instance Presentation

The following example links the MySQL TestDB database:

#!/usr/bin/python#-*-coding:utf-8-*-import mysqldb# Open database Connection db = MySQLdb.connect ("localhost", "testuser", "test123", " TESTDB ", charset= ' UTF8 ') # Use the cursor () method to get the cursor cursor = db.cursor () # Execute the SQL statement using the Execute method cursor.execute (" Select VERSION () ") # Use the Fetchone () method to obtain a data = Cursor.fetchone () print" Database version:%s "% data# close the connection db.close ()

The results from the above example are as follows:

Database version:5.0.45

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.