Python operation MySQL Database

Source: Internet
Author: User
Tags ossec

Learn python for a long time, did not write a script, first a MySQL database query script it.


1. To install MYSQLDB first

[[Email protected] ~]# pip install Mysql-python

Collecting Mysql-python

Downloading Mysql-python-1.2.5.zip (108kB)

100% |████████████████████████████████| 112kB 171kb/s

Building Wheels for collected Packages:mysql-python

Running setup.py bdist_wheel for Mysql-python ... done

Stored in directory:/root/.cache/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62

Successfully built Mysql-python

Installing collected Packages:mysql-python

Successfully installed mysql-python-1.2.5


2. The script is as follows

#!/usr/bin/env python# -*- coding: utf-8 -*-' Date:2016-11-08auther:bob ' Import  mysqldbdef python_mysql_query ():     #Open  the database  Connection    db = mysqldb.connect (host= ' localhost ', user= ' ossec ', passwd= ' Mysql0123 ', db= ' ossec ', port=3306, charset= ' UTF8 ')      #Gets  the operation  cursor    cursor = db.cursor ()      #SQL  statement  query     #sql  =  "Select * from data where id  <  '%d ' " %  (5)     sql = " select * from  Data limit 5 "    try:         #Execute  the sql statement        cursor.execute (SQL)                   #Receive  all return results         results = cursor.fetchall ()                   #Traverse  the print list         for i in results:             print i        except:         print  "Error: unable to fecth data"       #Close  the cursor    cursor.close ()           #Close  the database connection    db.close () if __name__== ' __main__ ':     python_mysql_query ()

This article is from "Kaka West" blog, please be sure to keep this source http://whnba.blog.51cto.com/1215711/1870648

Python operation MySQL Database

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.