Home >Backend Development >Python Tutorial >Introduction to the method of connecting to the database in python
This article mainly introduces the method of connecting to the database in python in detail, which has certain reference value. Interested friends can refer to it
The MYSQL module does not currently support python3.0 or above. version, since the python I downloaded is version 3.0, I can only use other methods to connect to the database.
The solutions for Python3.x to connect to MySQL include: oursql, PyMySQL, myconnpy, etc. Here we mainly install pymysql
1. Installation
pymysql installation : Find the location of the python folder pip program and open the command window:
pip install pymysql3
2. Use
After the installation is complete, the specific steps for database connection are as follows
Introduce the API module.
Get the connection to the database.
Execute SQL statements and stored procedures.
Close the database connection.
import pymysql #查询 #连接数据库 conn = pymysql.connect(host='数据库服务器名',user='用户名',passwd='密码',db='数据库名',pot='数据路端口号',charset='utf8') #获取游标 cur = conn.cursor() cur.execute('数据库查询语句') #获取数据,fetchone获取一条数据,fetchall获取全部数据 data = cur.fetchall() for d in data: print(d) #关闭游标 cur.close() #关闭数据库 conn.close() #插入、删除,修改操作 #连接数据库 conn = pymysql.connect(host='数据库服务器名',user='用户名',passwd='密码',db='数据库名',pot='数据路端口号',charset='utf8') #获取游标 cur = conn.cursor() cur.execute('数据库插入语句') #提交当前事务到数据库 conn.commit() #rowcount:返回数据条数或影响行数 print('插入:',cur.rowcount,'条数据') #关闭游标 cur.close() #关闭数据库 conn.close()
You can add a try...except statement to the database operation to catch errors. When an error occurs, you can roll back the database operation and go back to before modification:
try: # 执行sql语句 cur.execute(sql) # 提交到数据库执行 cur.commit() except: # 发生错误时回滚 cur.rollback() # 关闭游标 cur.close() #关闭数据库 conn.close()
The above is the detailed content of Introduction to the method of connecting to the database in python. For more information, please follow other related articles on the PHP Chinese website!