This article mainly for you in detail the Python connection database method, with a certain reference value, interested in small partners can refer to
MySQL module temporarily does not support python3.0 above, because I download Python is version 3.0, so you want to connect to the database can only use other methods.
python3.x connection MySQL program has: Oursql, Pymysql, MYCONNPY, etc., here is mainly installed Pymysql
1. Installation
Pymysql Installation: Find the location of the Python folder pip program to open the command window:
Pip Install Pymysql3
2. Use
After the installation is complete, the following steps are followed for the database connection
Introduce API modules.
Gets the connection to the database.
Executes SQL statements and stored procedures.
Close the database connection.
Import pymysql# Query # CONNECTION Database conn = pymysql.connect (host= ' database server name ', user= ' username ', passwd= ' password ', db= ' database name ', pot= ' data port Port ', charset= ' UTF8 ') #获取游标cur = Conn.cursor () cur.execute (' database query statement ') #获取数据, Fetchone get a piece of data, fetchall get all data = Cur.fetchall () for D in Data:print (d) #关闭游标cur. Close () #关闭数据库conn. Close () #插入, delete, modify operation # Connect to Database conn = Pymysql.connect (host= ' Database server name ', user= ' user name ', passwd= ' password ', db= ' database name ', pot= ' data port number ', charset= ' utf8 ') #获取游标cur = Conn.cursor () cur.execute (' Database INSERT statement ') #提交当前事务到数据库conn. Commit () #rowcount: Returns the number of data bars or affects the number of rows print (' Insert: ', Cur.rowcount, ' bar data ') #关闭游标cur. Close () # Close Database Conn.close ()
The operation of the database can be added to the try...except statement catch error, when an error occurs, you can rollback the database operation, back to the modification:
Try: # Execute SQL statement cur.execute (SQL) # Commit to Database Execution Cur.commit () except: # Rollback when an error occurs cur.rollback () # Close cursor cur.close () #关闭数据库conn. Close ()