Use the MySQLdb module in Python

Source: Internet
Author: User

1. Import Module
Import MySQLdb >>> help ('mysqldb ')
>>> Help ('mysqldb. cursors ')
2. Connect to the database
Conn = MySQLdb. Connection (host = 'host', user = 'user', passwd = 'Password', db = 'dbname', port = port)

For example:

Conn = connect (host = '10. 0. *. * ', user = 'root', db = 'mysql', port = 3306, passwd = 'test ')

Meaning:
Host: ip address of the host that needs to be connected to Mysql
User: user name used to connect to mysql
Password: user name and password used for connection
Dbname: Default opened database
If you need to switch to another database of the user after the connection is successful, use the following statement:
Conn. select_db ('database name') 3. Obtain the database operation cursor (pointer)
Because the underlying layer of this module actually calls c api, you must first obtain the pointer to the database.
Cur = conn. cursor () 4. Database Operations
Execute the SQL query statement using the pointer object first:
Cur.exe cute ('select * from tables ')
The returned value is the number of rows obtained by the SQL statement. For example, 2L indicates 2 rows.
Then, you can obtain the row information from the fetchone or fetchall methods of the object.
The fetchone () method of the pointer object is to get the tuple return value of a row each time:
  1. >>> Result = cur. fetchone ()
  2. >>>PrintResult
The fetchall () method of the pointer object is to obtain a set of tuple values composed of row information:
  1. >>> Cur. scroll (0,'Absolute')
  2. >>> Result = cur. fetchall ()
  3. >>>PrintResult
  • 1
  • 2
  • Next Page

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.