Article Directory
Python operation mysql database
Python operates the mysql database, you need to use the third library:pymysql
1. mysql installation
Official website: https://www.mysql.com/
2. Install pymysql
pip install PyMySql -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
Three, use
Code demo:
import pymysql
conn = pymysql.connect(host="localhost",
user ="student",
password="student",
database="studentmanagementsystem",
port=3306,
charset="utf-8")
#获取游标对象
cursor =conn.cursor()
#执行
sql = "select * from student"
cursor.execute(sql)
#关闭数据库连接和游标
cursor.close()
conn.close()
1. Guide package
import pymysql
2. Create a database connection
conn = pymysql.connect(host="localhost",
user ="student",
password="student",
database="studentmanagementsystem",
port=3306,
charset="utf-8")
illustrate:
- host : database server connection address
- user : login username
- password : password
- database : the name of the database to connect to
- port : The database connection is broken (default 3306)
- charset: character set (set to utf-8)
- autocommit: Whether to automatically submit
- True: autocommit
- False: Submit manually
3. Get the cursor object
cursor = conn.cursor()
illustrate
-
- Call the cursor() method of the database connection object to get the cursor object
4. Perform addition, deletion, modification and query operations
sql = "select * from student"
cursor.execute(sql)
illustrate
- Call the execute() method of the cursor object to execute the SQL statement
- sql: the sql statement to be executed
Inquire
- Returns the first result found in the query
result1 = cursor.fetchone()
print(f"查询到的第一个结果:{result1}")
-
The number of results returned by the query can be specified by size, and the first query result is returned by default. Return value:
((),())
result2 = cursor.fetchmany(size=2); print(f"查询2 行的数据:{result2}")
-
Get the data of all rows in the result set, the return value is:
((),(),..)
result3=cursor.fetchall() print(f"查询全部数据:{result3}")
-
Get the total number of records in the result set:
rowcount
count = cursor.rowcount print(f"student表中有{count}条数据")
additions, deletions
train of thought
1.导包
try:
程序前期,需要执行的代码
2.创建连接对象
3.获取游标对象
4.执行sql
+ 在图书表中插入一行数据
+ 主动抛出异常
+ 在英雄人物表中插入一行数据
调用提交事务:conn.commit()
except:
程序出现异常后,处理代码
调用事务回滚:conn.rollback()
finally:
程序结束时,需要执行的代码
5.关闭游标
6.关闭连接
operate
- Autocommit (not recommended):
autocommit = True
- Manual submission (recommended):
- Submit the transaction:
conn.commit()
- Rollback transaction:
conn.rollback
- Submit the transaction:
sample code
# 1. 导包
import pymysql
# 2. 创建数据库连接
conn = pymysql.connect(host="localhost",
user ="student",
password="student",
database="studentmanagementsystem",
port=3306)
cursor = conn.cursor()
try:
#这里sql可以是update,insert,delete语句
sql = "UPDATE student SET stu_name='ccx330' where stu_id ='00006'";
print(sql)
cursor.execute(sql)
# 提交事务
conn.commit()
print(cursor.rowcount)
except Exception as e:
#回滚事务
conn.rollback()
raise e
finally:
cursor.close()
conn.close()
4. Packaging tools
General database information will be placed in a single place
- separate py file
- stored in environment variable
#config.py
__config = {
"host":"127.0.0.1",
"user":"student",
"password":"student",
"database":"studentmanagementsystem",
"port":3306,
"charset":"utf8"
}
config = __config
Package database file
#db_funs.py
#导包
from config import config
class DButils(object):
#初始化
__conn = None
_cursour=None
#DB_utils.py
import logging
import pymysql
from Python.python_SQL.config import config
class DButils():
def __init__(self):
self.__conn=None
self.__cursor = None
#创建连接
def __get_conn(self):
if self.__conn is None:
self.__conn=pymysql.connect(**config)
return self.__conn
#获取游标
def __get_cursor(self):
if self.__cursor is None:
self.__cursor = self.__get_conn().cursor()
return self.__cursor
#执行sql
def exec_sql(self,sql):
try:
#获取游标对象
cursor = self.__get_cursor()
# 调用游标对象的execute方法,执行sql
cursor.execute(sql)
# sql = "select * from xxx" # sql = "update delete insert"
# 如果是查询
if sql.split()[0].lower() == "select": # sql语句中的第一个元素是不是select
# 返回所有数据
return cursor.fetchall()
# 否则:
else:
# 提交事务
self.__conn.commit()
# 返回受影响的行数
return cursor.rowcount # 增删改返回的的影响行数rowcount
pass
except Exception as e:
self.__conn.rollback()
# 打印异常信息
print(e)
logging.info("数据库异常:{}".format(e))
finally:
self.__close_cursor()
self.__close_conn()
# 关闭游标
def __close_cursor(self):
if self.__cursor:
self.__cursor.close()
self.__cursor= None
#关闭数据库
def __close_conn(self):
if self.__conn:
self.__conn.close()
self.__conn= None
test
#main.py
from Python.python_SQL.DB_utils import DButils
if __name__ == '__main__':
print("测试pyhon操作数据库")
db = DButils()
#查询
sql = "select * from student"
print(db.exec_sql(sql))
#
sql1 = "INSERT INTO student " \
" VALUES " \
"('00011','莫彬', 0,'2005-08-11', '黑龙江省', '15604653586', '云南省南京市崇文黄路Q座 671564','201149', '[email protected]', '发布')"
print(db.exec_sql(sql1))
sql = "select * from student"
print(db.exec_sql(sql))
Note: Where is the DButils class located?