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