Install MySQL-python module to execute database operation method
This article mainly introduces how to install the MySQL-python module to perform database operation, hoping to supplement and update some knowledge, if you have other questions to understand, you can continue to follow my updated article in the industry information.
To perform database operations in python, first install the MySQL-python module
Through the command: yum install-y MySQL-python
Common actions:
Create a database connection:
Conn = MySQLdb.connect (
Host='127.0.0.1'
User='test'
Passwd='test'
Db='test01'
Port=3306
Charset=utf8)
Cur = conn.cursor () # create cursors through the cursor () method under the acquired database connection conn, output in meta-ancestor form, and output in conn.cursor (MySQLdb.cursors.DictCursor) # dictionary form
Conn.selecct_db (dbname) # Select a database
Cur.execute (sql statement) # is used to execute the corresponding sql statement
Cur.fetchall () # get query result
Cur.scroll (position, mode) # adjust pointer
Cur.rollback () # rollback when an error occurs
Cur.close () # close the cursor
The conn.commit () # method must be used when committing a transaction and inserting data into the database, otherwise the data will not be actually inserted
Conn.close () # close the database connection
Example:
#! / usr/bin/env python#coding:utf8import MySQLdbdef mysqlconnet (): try: conn = MySQLdb.connect (host= "127.0.0.1", user= "test", passwd= "test", db= "test01", port=3306,charset= "utf8") cur = conn.cursor () except Exception,e: print "\ 033 [31 m% s\ 033 [0m"% e return conn,curdef select (): conn Cur=mysqlconnet () sql = "select * from machineinfo" "# sql statement executed try: cur.execute (sql) result=cur.fetchall () for line in list (result): print line [0], line [1] except Exception,e: print"\ 033 [31m% s\ 033 [0m "% e cur.close () conn.close () if _ _ name__ = ='_ main__': select ()
Read the above about the installation of MySQL-python module to implement the database operation method, I hope it can bring some help to everyone in practical application. Due to the limited space in this article, it is inevitable that there will be deficiencies and need to be supplemented. If you need more professional answers, you can contact us on the official website for 24-hour pre-sales and after-sales to help you answer questions at any time.