Python connects to MySQL database

Source: Internet
Author: User

Install and start the MySQL database under Linux and Windows

Python installs the MYSQLDB package, it is recommended to use PIP installation

Here's how to use PIP:

Yum Install Python-pip (priority installation Python-pip to use PIP)

Pip is similar to Yum in Linux

Pip Install Ipython (install Python completion tool)

Pip Uninstall Ipython (uninstall Ipython with PIP)

PIP List (see which packages are installed)

Pip Install ipython==1.2.1 (for python2.6 version)


Python connection MySQL

Example:

Define a Connect_mysql function that specifies the MySQL connection parameter in the function, as shown below

Import MySQLdb

Def connect_mysql ():

Db_config = {

' Host ': ' 192.168.1.1 ',

' Port ': 3306,

' User ': ' Zabbix ',

' passwd ': ' 123456 ',

' DB ': ' Zabbix_user ',

' CharSet ': ' UTF8 '

}

Try

CNX = MySQLdb.connect (**db_config)

Except Exception as E:

Raise E

Return CNX

Connect_mysql ()

Cursor operations

Example:

Import MySQLdb

Def connect_mysql ():

Db_config = {

' Host ': ' 192.168.48.128 ',

' Port ': 3306,

' User ': ' Xiang ',

' passwd ': ' 123456 ',

' db ': ' Python ',

' CharSet ': ' UTF8 '

}

Try

CNX = MySQLdb.connect (**db_config)

Except Exception as E:

Raise E

Return CNX

if __name__ = = ' __main__ ':

CNX = Connect_mysql ()

#cursor (): Creating a Cursor Object

cus = Cnx.cursor ()

sql = "CREATE TABLE test (ID int not null); INSERT into test (ID) values (100);

Try

#excute (sql[, args]): Execute a database query or command

Cus.execute (SQL)

#close (): Close this Cursor object

Cus.close ()

#提交游标对象

Cnx.commit ()

Except Exception as E:

#回滚游标对象到commi之前

Cnx.rollback ()

Raise E

Finally

Cnx.close ()


This article is from the "Coarse bread" blog, make sure to keep this source http://culiangmianbao.blog.51cto.com/10475024/1983635

Python connects to 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.