PyMySql介绍
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个第三方库,Python2中则使用mysqldb。
PyMySql安装
可以通过pip直接安装也可以通过pycharm的settings中进行安装;
pip install pymysqlPyMySql处理数据库增删改查
说明:以下代码都是python3.8版本,表结构是id、name、age,其中id设置为自动增长
增
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: MysqlTest.py#Author: mutou#Date: 2020/5/31 18:44#Description:对mysql进行数据库操作#--------------------------------------------------------------------------#实现mysql数据库操作的步骤:import pymysql#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")#2.需要获取游标,用于执行sql语句并存储结果集get_cursor=get_conn.cursor()#3.定义sql语句:str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"username = "wood"age = 20#4.通过游标:执行sql语句get_cursor.execute(str_sql, [username, age])#5.事务:针对修改、删除、增加是需要操作事务,即事务提交get_conn.commit()#6.将数据库对象进行关闭get_conn.close()执行结果如下:
插入数据失败回滚
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: MysqlTest.py#Author: mutou#Date: 2020/5/31 18:44#Description:对mysql进行数据库操作#--------------------------------------------------------------------------#实现mysql数据库操作的步骤:import pymysql#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")#2.需要获取游标,用于执行sql语句并存储结果集get_cursor=get_conn.cursor()#3.定义sql语句:str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"username = "wood_test"age = 29#4.通过游标:执行sql语句try: # 执行SQL语句 get_cursor.execute(str_sql, [username, age]) #再执行一个sql语句,错误的sql语句 get_cursor.execute(str_sql,username) # 提交事务 get_conn.commit()except Exception as e: # 有异常,回滚事务 get_conn.rollback() print("抛出异常,事务回滚")#5.事务:针对修改、删除、增加是需要操作事务,即事务提交get_conn.commit()#6.将数据库对象进行关闭get_conn.close()执行结果如下:数据库中数据不插入第一条数据
获取插入数据的ID(关联操作时会用到)
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: MysqlTest.py#Author: mutou#Date: 2020/5/31 18:44#Description:对mysql进行数据库操作#--------------------------------------------------------------------------#实现mysql数据库操作的步骤:import pymysql#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")#2.需要获取游标,用于执行sql语句并存储结果集get_cursor=get_conn.cursor()#3.定义sql语句:str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"username = "wood_id"age = 22#4.通过游标:执行sql语句try: # 执行SQL语句 get_cursor.execute(str_sql, [username, age]) # 提交事务 get_conn.commit() # 提交之后,获取刚插入的数据的ID last_id = get_cursor.lastrowid print("最后一条数据的ID是:", last_id)except Exception as e: # 有异常,回滚事务 get_conn.rollback() print("事务回滚,出现异常")#5.事务:针对修改、删除、增加是需要操作事务,即事务提交get_conn.commit()#6.将数据库对象进行关闭get_conn.close()执行结果如下:
批量执行
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: MysqlTest.py#Author: mutou#Date: 2020/5/31 18:44#Description:对mysql进行数据库操作#--------------------------------------------------------------------------#实现mysql数据库操作的步骤:import pymysql#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")#2.需要获取游标,用于执行sql语句并存储结果集get_cursor=get_conn.cursor()#3.定义sql语句:str_sql = "INSERT INTO user_test(name, age) VALUES (%s, %s);"data = [("Tom", 18), ("Jack", 20), ("Jerry", 22)]#4.通过游标:执行sql语句try: # 批量执行多条插入SQL语句 get_cursor.executemany(str_sql, data) # 提交事务 get_conn.commit()except Exception as e: # 有异常,回滚事务 get_conn.rollback() print("事务回滚")#5.事务:针对修改、删除、增加是需要操作事务,即事务提交get_conn.commit()#6.将数据库对象进行关闭get_conn.close()执行结果如下:
删
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: MysqlTest.py#Author: mutou#Date: 2020/5/31 18:44#Description:对mysql进行数据库操作#--------------------------------------------------------------------------#实现mysql数据库操作的步骤:import pymysql#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")#2.需要获取游标,用于执行sql语句并存储结果集get_cursor=get_conn.cursor()#3.定义sql语句:str_sql = "DELETE FROM user_test WHERE id=%s;"#4.通过游标:执行sql语句try: # 批量执行多条插入SQL语句 get_cursor.execute(str_sql, 5) # 提交事务 get_conn.commit()except Exception as e: # 有异常,回滚事务 get_conn.rollback() print("事务回滚")#5.事务:针对修改、删除、增加是需要操作事务,即事务提交get_conn.commit()#6.将数据库对象进行关闭get_conn.close()执行结果如下:
执行结果如下:
执行结果如下:
查询单条数据
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: MysqlTest.py#Author: mutou#Date: 2020/5/31 18:44#Description:对mysql进行数据库操作#--------------------------------------------------------------------------#实现mysql数据库操作的步骤:import pymysql#1.创建数据库连接:连接的信息:数据库服务器地址、用户名、密码、数据库名get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test")#2.需要获取游标,用于执行sql语句并存储结果集get_cursor=get_conn.cursor()#3.定义sql语句:sql = "select * from user_test where id=2"# 4.获取单条查询数据get_cursor.execute(sql)ret = get_cursor.fetchone()get_cursor.close()get_conn.close()# 打印下查询结果print(ret)执行结果如下:
数据库中插入一万条数据
项目结构:
其中造数据模块Create_Data:
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: Create_Data.py#Author: mutou#Date: 2020/6/2 21:00#Description:造数据:要求:姓名必须是6-12位,性别随机、年龄18-100之间随机;#数据的条件:可以通过python 程序直接判定,同样的可以联想到数据库做数据检查#--------------------------------------------------------------------------import randomimport stringclass CreateData(object): #造一万条:姓名随机造数据要求6-12位 #可以从数字、字母、符号等进行随机取值;还可以从网络上获取一些文字,数据进行筛选; #python自带有一个string模块,该模块可以获取对应的所有字符串 def get_name(self): str_char="" #随机选值的容器:数字、大小写、符号 get_char=string.ascii_letters+string.digits #+string.punctuation #定义随机的6-12位的数字 get_len=random.randint(6,12) for i in range(1,get_len+1): str_char+=random.choice(get_char) return str_char #性别的操作 def get_sex(self): return random.choice(["男","女"]) #年龄的数据 def get_age(self): return random.randint(18,100) #声明一个方法进行,一条数据将其放在一个列表 def get_one_data(self): #此处返回的数据顺序最好与创建表时结构顺序一致,便于插入数据时一一对象 return [self.get_name(),self.get_sex(),self.get_age()] if __name__=="__main__": #测试代码 create=CreateData() print(create.get_name()) print(create.get_one_data())数据库插入数据模块:
#-*- coding:utf-8 -*-##-------------------------------------------------------------------------#ProjectName: Python2020#FileName: Conn_Mysql.py#Author: mutou#Date: 2020/6/2 21:15#Description:连接mysql数据库,完成数据插入操作#--------------------------------------------------------------------------import pymysqlfrom Day14.Data_Opera.Create_Data import CreateDataclass ConnMysql(object): #获取数据库连接: def __init__(self): self.get_conn=pymysql.connect(host="123.57.71.195",user="wood",password="123456",database="python_test") #创建游标 self.get_cursor=self.get_conn.cursor() #定义sql语句并通过游标执行 def create_table(self,tablename): #定义创建表的sql语句,其实此处可以将字段全部设置为不定长参数 str_sql="create table %s(student_id int,student_name varchar(20),student_sex char(4),student_age int);"%(tablename) #通过游标进行执行sql语句 self.get_cursor.execute(str_sql) #定义插入数据的 def insert_data(self,tablename,*args): #此处需要考虑如何插入,插入数据的可以定义四个参数,也可以定义不定长 #此处考虑引号、转义符;如果姓名存在转义符或者引号的话则需要在此添加转义符 #str_sql="insert into %s values(%s,'%s','%s',%s)"%(tablename) str_sql = "insert into student_test values(%s,%s,%s,%s);" # print(str_sql) #self.get_cursor.execute(str_sql) print(str_sql) #讲执行效率 self.get_cursor.executemany(str_sql,args) #测试出一个参数的情况 #self.get_cursor.executemany("insert into student values(%s)",args) #等价的是for argv in args: #self.get_cursor.execute("insert into student values(%s)",argv) self.get_conn.commit() #定义一个关闭对象的方法 def close_conn(self): self.get_conn.close() #测试代码:以后的测试代码都会定义在main方法中#__name__在当前模块其值就是mainif __name__=="__main__": conn=ConnMysql() createdata=CreateData() #conn.create_table("student_test") #插入一万条数据 #获取一组数据 list1=[] for i in range(1,10001): get_one=createdata.get_one_data() get_one.insert(0,i) list1.append(get_one) conn.insert_data("student_test",*list1) #conn.insert_data(*[i for i in range(1,100)]) conn.close_conn()
