Learn how to write Python simple and simple to connect to a database and perform query operations

Source: Internet
Author: User
Python connects to the database operation by doing the following:

In the native MySQL database there is a library named Yao, which has a table named user, the contents of the table

The following is how Python connects to the database and finds out what is in the table, with the following code:

#! /usr/bin/python# filename  conn.pyimport mysqldb         # Load Connection Database module try  :              # Attempt to connect to database    conn = MySQLdb.connect ("localhost", "root", "www", "Yao", charset= "UTF8")  # defines the information that connects the database except Mysqldb.operationalerror, Message:  # connection failure prompt    print "link error" cursor=conn.cursor ()          #定义连接对象cursor. Execute ("SELECT * from User")  #使用cursor提供的方法来执行查询语句data =cursor.fetchall ()         #使用fetchall方法返回所有查询结果print data              #打印查询结果cursor. Close ( )            #关闭cursor对象conn. Close ()             #关闭数据库链接

The result of the program execution is

  • 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.