manipulating MySQL with Python

Source: Internet
Author: User

Usually the main programming language is Java, the development of the main use of MySQL, often in order to test, debugging purposes need to operate the database, such as backup, insert test data, modify test data, some times can not be simple with SQL to complete the task, or are very good to complete the task, write in Java and a little too troublesome , I think of Python. Python syntax is concise, without compiling, can be better to complete the task. Today, I looked at Python's operation on MySQL and made a note of it.

First of all, install the required environment, MySQL and Python will not say, necessary things.

Mainly installs the MySQLdb, may go to sf.net to download, the specific address is http://sourceforge.net/projects/mysql-python/

If you use Ubuntu, direct

sudo apt-get install Python-mysqldb

After the installation is complete, you can test it in the Python interpreter

Input

Python code
    1. Import mysqldb #注意大小写!!

If you do not make an error, it proves that the installation was successful and may continue


MySQLdb in Python is equivalent to the Java MySQL JDBC Driver,python also has a similar data interface Specification Python DB API,MYSQLDB is the implementation of MySQL. The operation is also relatively simple and other platforms or language operations database, is to establish a connection to the database system, and then to the database input SQL, and then get the results from the database.

First write the simplest, create a database:

Python code
  1. #!/usr/bin/env python
  2. #coding =utf-8
  3. ###################################
  4. # @author Migle
  5. # @date 2010-01-17
  6. ##################################
  7. #MySQLdb Example
  8. #
  9. ##################################
  10. Import MySQLdb
  11. #建立和数据库系统的连接
  12. conn = MySQLdb.connect (host=' localhost ', user=' root ', passwd=' longforfreedom ')
  13. #获取操作游标
  14. cursor = Conn.cursor ()
  15. #执行SQL, create a database.
  16. Cursor.execute ("" "Create Database Python" ")
  17. #关闭连接, freeing up resources
  18. Cursor.close ();

Create a database, create a table, insert data, insert multiple data

Python code
  1. #!/usr/bin/env python
  2. #coding =utf-8
  3. ###################################
  4. # @author Migle
  5. # @date 2010-01-17
  6. ##################################
  7. #MySQLdb Example
  8. #
  9. ##################################
  10. Import MySQLdb
  11. #建立和数据库系统的连接
  12. conn = MySQLdb.connect (host=' localhost ', user=' root ', passwd=' longforfreedom ')
  13. #获取操作游标
  14. cursor = Conn.cursor ()
  15. #执行SQL, create a database.
  16. Cursor.execute ("" "Create database if not exists Python " ")
  17. #选择数据库
  18. conn.select_db (' python ');
  19. #执行SQL, create a data table.
  20. Cursor.execute ("" "CREATE TABLE test (ID int, info varchar )" "")
  21. Value = [1,"inserted?"];
  22. #插入一条记录
  23. Cursor.execute ("INSERT into test values (%s,%s)", value);
  24. Values=[]
  25. #生成插入参数值
  26. For I in range:
  27. Values.append ((i,' Hello mysqldb, I am recoder ' + str (i)))
  28. #插入多条记录
  29. Cursor.executemany ("" "insert into test values (%s,%s)" ", values);
  30. #关闭连接, freeing up resources
  31. Cursor.close ();

The process of querying and inserting is similar, just one more step to get the results of the query

Python code
    1. #!/usr/bin/env python
    2. #coding =utf-8
    3. ######################################
    4. #
    5. # @author Migle
    6. # @date 2010-01-17
    7. #
    8. ######################################
    9. #
    10. # MYSQLDB Query
    11. #
    12. #######################################
    13. Import MySQLdb
    14. conn = MySQLdb.connect (host=' localhost ', user=' root ', passwd=' longforfreedom ', db=' python ')
    15. cursor = Conn.cursor ()
    16. Count = Cursor.execute (' select * from Test ')
    17. Print ' has a total of%s records ', Count
    18. #获取一条记录, each record is returned as a single tuple
    19. Print "Get only one record:"
    20. result = Cursor.fetchone ();
    21. Print result
    22. #print ' ID:%s info:%s '% (Result[0],result[1])
    23. Print ' ID:%s info:%s '% result
    24. #获取5条记录, note that because Fetchone () was previously executed, the cursor already refers to the second record, that is, all records starting from the second bar
    25. Print "Get only 5 records:"
    26. Results = Cursor.fetchmany (5)
    27. For R in results:
    28. Print R
    29. Print "Get all results:"
    30. #重置游标位置, 0, offset, Mode=absolute | Relative, default is relative,
    31. Cursor.scroll (0,mode=' absolute ')
    32. #获取所有结果
    33. Results = Cursor.fetchall ()
    34. For R in results:
    35. Print R
    36. Conn.close ()

manipulating MySQL with Python

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.