Connect to MySQL using MySQLdb in Python

Source: Internet
Author: User

First of all, the environment required for installation is not mentioned in Mysql and Python.

MySQLdb is installed.

Free in http://linux.bkjia.com/

The username and password are both www.bkjia.com

The specific download directory is/pub/2011/08/26/Python. Use MySQLdb to connect to MySQL/MySQLdb/

If Ubuntu is used, run sudo apt-get install python-mysqldb directly. After the installation is complete, test it in the Python interpreter and enter

Import MySQLdb # case sensitive !! If no error is reported, the installation is successful and may continue.

First, write the simplest one to create a database:

  1. #! /Usr/bin/env python
  2. # Coding = UTF-8
  3. ImportMySQLdb
  4. # Establish a connection to the Database System
  5. Conn = MySQLdb. connect (host ='Localhost', User ='Root', Passwd ='Longforfreedom')
  6. # Retrieve operation cursor
  7. Cursor = conn. cursor ()
  8. # Execute SQL to create a database.
  9. Cursor.exe cute ("Create database python """)
  10. # Close the connection and release resources
  11. Cursor. close ();
Create databases, create tables, insert data, and insert multiple data records
  1. #! /Usr/bin/env python
  2. # Coding = UTF-8
  3. ImportMySQLdb
  4. # Establish a connection to the Database System
  5. Conn = MySQLdb. connect (host ='Localhost', User ='Root', Passwd ='Longforfreedom')
  6. # Retrieve operation cursor
  7. Cursor = conn. cursor ()
  8. # Execute SQL to create a database.
  9. Cursor.exe cute ("Create database if not exists python """)
  10. # Selecting a database
  11. Conn. select_db ('Python');
  12. # Execute SQL to create a data table.
  13. Cursor.exe cute ("Create table test (id int, info varchar (100 ))""")
  14. Value = [1,"Inserted? "];
  15. # Insert a record
  16. Cursor.exe cute ("Insert into test values (% s, % s )", Value );
  17. Values = []
  18. # Generating insert parameter values
  19. ForIInRange (20):
  20. Values. append (I,'Hello mysqldb, I am recoder'+ Str (I )))
  21. # Insert multiple records
  22. Cursor.exe cute.pdf ("Insert into test values (% s, % s )""", Values );
  23. # Close the connection and release resources
  24. Cursor. close ();
The query process is similar to the insert process, but there is only one more step to get the query result.
 
  1. #! /Usr/bin/env python
  2. # Coding = UTF-8
  3. ImportMySQLdb
  4. Conn = MySQLdb. connect (host ='Localhost', User ='Root', Passwd ='Longforfreedom', Db ='Python')
  5. Cursor = conn. cursor ()
  6. Count = cursor.exe cute ('Select * from Test')
  7. Print 'Total % s record records', Count
  8. # Obtain a record. Each record is returned as a tuples.
  9. Print "Get only one record :"
  10. Result = cursor. fetchone ();
  11. PrintResult
  12. # Print 'id: % s info: % s' % (result [0], result [1])
  13. Print 'Id: % s info: % s'% Result
  14. # Obtain five records. Note that the cursor has pointed to the second record because fetchone () was previously executed, that is, all records starting from the second record.
  15. Print "Get only five records :"
  16. Results = cursor. fetchtasks (5)
  17. ForRInResults:
  18. PrintR
  19. Print "Get all results :"
  20. # Reset the cursor position. The value 0 indicates the offset. mode = absolute | relative. The default value is relative,
  21. Cursor. scroll (0, Mode ='Absolute')
  22. # Getting all results
  23. Results = cursor. fetchall ()
  24. ForRInResults:
  25. PrintR
  26. Conn. close ()

Related Article

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.