How to connect python to the database: how to connect python to the database
Currently, the MYSQL module does not support python 3.0 or later versions. Since python is downloaded, you can only use other methods to connect to the database.
Python3.x provides the following solutions to connect to MySQL: oursql, PyMySQL, and myconyy. Here, we mainly install pymysql.
1. Install
Install pymysql: Find the pip program in the python folder and open the command window:
Pip install pymysql3
2. Use
After installation, perform the following steps to connect to the database:
Introduce the API module.
Obtain the connection to the database.
Execute SQL statements and stored procedures.
Close the database connection.
Import pymysql # query # connect to the database conn = pymysql. connect (host = 'database server name', user = 'username', passwd = 'Password', db = 'database name', pot = 'data path port number ', charset = 'utf8') # obtain the cursor cur = conn.cursor()cur.exe cute ('database query statement') # obtain data, fetchone gets a piece of data, and fetchall gets all data = cur. fetchall () for d in data: print (d) # Close the cursor cur. close () # close database conn. close () # insert, delete, modify operation # connect to database conn = pymysql. connect (host = 'database server name', user = 'username', passwd = 'Password', db = 'database name', pot = 'data path port number ', charset = 'utf8') # obtain the cursor cur = conn.cursor()cur.exe cute ('database insert statement') # submit the current transaction to the database conn. commit () # rowcount: number of returned data records or number of affected rows print ('insert: ', cur. rowcount, 'data') # Close the cursor cur. close () # close database conn. close ()
During database operations, you can add the try... failed t statement to catch errors. When an error occurs, you can roll back the database and go back to the modification:
Try: # Run the SQL statement cur.exe cute (SQL) # submit it to the database and execute cur. commit () commit T: # Roll Back cur when an error occurs. rollback () # Close the cursor cur. close () # close database conn. close ()
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.