首页 > 数据库 >python: read mysql

python: read mysql

时间:2023-06-15 22:45:03浏览次数:37  
标签:BookKindName BookKindParent python self geovindu cursor read BookKindList mysql

sql:

create database geovindu;

use geovindu;

drop table BookKindList;
#书目录
create table BookKindList
(
    BookKindID INT NOT NULL AUTO_INCREMENT, #自动增加
    BookKindName nvarchar(500) not null,
    BookKindParent int null,
   PRIMARY KEY(BookKindID)  #主键
);

insert into BookKindList(BookKindName,BookKindParent) values("六福书目录",0);


#删除
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`DeleteBookKind` $$
CREATE PROCEDURE `geovindu`.`DeleteBookKind` (IN param1 INT)
BEGIN
         Delete From bookkindlist WHERE BookKindID = param1;
END $$
DELIMITER ;
 
delete from bookkindlist WHERE BookKindID =10;
 
 
SELECT * FROM bookkindlist;
    
 execute DeleteBookKind(10);
  
  
  
#查询所有
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`proc_Select_BookKindListAll` $$
CREATE PROCEDURE `geovindu`.`proc_Select_BookKindListAll` ()
BEGIN
    SELECT * FROM bookkindlist;
END $$
DELIMITER ;
  
 DROP PROCEDURE proc_Select_BookKindListAll;
  
  
  
select * from  `geovindu`.`bookkindlist`;
SELECT * FROM bookkindlist;
  
#统计
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`BookKindCount` $$
CREATE PROCEDURE `geovindu`.`BookKindCount` (OUT param1ID INT)
BEGIN
        select COUNT(*) into param1ID  From bookkindlist;
END $$
DELIMITER ;
  
#更新
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`proc_Update_BookKindList` $$
CREATE PROCEDURE `geovindu`.`proc_Update_BookKindList` (IN param1ID Int,IN param1Name NVarChar(1000),IN param1Parent Int)
BEGIN
IF NOT EXISTS (SELECT * FROM BookKindList WHERE BookKindName=param1Name) then #如果存在相同的记录,不更新名称
UPDATE BookKindList
    SET
        BookKindName=param1Name ,
        BookKindParent=param1Parent
    where
        BookKindID=param1ID;
ELSE
    UPDATE BookKindList
    SET BookKindParent=param1Parent
    where
        BookKindID=param1ID;
END IF;
END $$
DELIMITER ;
  
  
#查询一条
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`proc_Select_BookKindList` $$
CREATE PROCEDURE `geovindu`.`proc_Select_BookKindList` (IN param1 INT)
BEGIN
        SELECT * FROM BookKindList WHERE BookKindID = param1;
END $$
DELIMITER ;
  
#插入一条
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`proc_Insert_BookKindList` $$
CREATE PROCEDURE `geovindu`.`proc_Insert_BookKindList` (IN param1Name NVarChar(1000),IN param1Parent Int)
BEGIN
        insert into BookKindList(BookKindName,BookKindParent) values(param1Name,param1Parent);
END $$
DELIMITER ;
  
#插入一条返回值
DELIMITER $$
DROP PROCEDURE IF EXISTS `geovindu`.`proc_Insert_BookKindOut` $$
CREATE PROCEDURE `geovindu`.`proc_Insert_BookKindOut` (IN param1Name NVarChar(1000),IN param1Parent Int,OUT ID INT)
BEGIN
     IF NOT EXISTS (SELECT * FROM BookKindList WHERE BookKindName=param1Name) then   #如果存在相同的记录,不添加
        INSERT INTO BookKindList (BookKindName,BookKindParent)VALUES(param1Name ,param1Parent);
        #set ID=Last_insert_id()
        SELECT LAST_INSERT_ID() into ID;
      end if;
END $$
DELIMITER ;

  

 

"""
bookkind.py  书目录类
读取excel文件数据
date 2023-06-15
edit: Geovin Du,geovindu, 涂聚文
ide: PyCharm 2023.1 python 11

"""

import sys
import os

class BookKindList(object):

    def __init__(self, BookKindID, BookKindName, BookKindParent):
        """
        保险类  构造函数
        :param  BookKindID:  自增ID
        :param  BookKindName:  书目录名
        :param  BookKindParent:  父ID
        """
        self.__BookKindID = BookKindID
        self.__BookKindName = BookKindName
        self.__BookKindParent = BookKindParent


    def getBookKindID(self):
        """
        得到自增ID
        :return:  返回自增ID
        """
        return self.__BookKindID


    def setBookKindID(self, BookKindID):
        """
        自增ID
        :param  BookKindID:  ID
        :return:  none
        """
        self.__BookKindID = BookKindID


    def getBookKindName(self):
        """
        获取书目录名
        :return:  返回书类目名
        """
        return self.__BookKindName


    def setBookKindName(self, BookKindName):
        """
        设置书目录名
        :param  BookKindName:  书类名
        :return:  none
        """
        self.__BookKindName = BookKindName


    def getBookKindParent(self):
        """
        获取父ID
        :return:  返回月份
        """
        return self.__BookKindParent


    def setBookKindParent(self, BookKindParent):
        """
        设置父ID
        :param  BookKindParent:  输入父ID
        :return:  none
        """
        self.__BookKindParent = BookKindParent


    def __str__(self):
        return f"BookKindID:  {self.__BookKindID},  BookKindName:  {self.__BookKindName},  BookKindParent:  {self.__BookKindParent}"




"""
MySQLDAL.py
读取MySQL数据
date 2023-06-15
edit: Geovin Du,geovindu, 涂聚文
ide: PyCharm 2023.1 python 11
参考:
https://www.mssqltips.com/sqlservertip/6694/crud-operations-in-sql-server-using-python/
https://learn.microsoft.com/zh-cn/sql/connect/python/pymssql/step-3-proof-of-concept-connecting-to-sql-using-pymssql?view=sql-server-ver16
https://docs.sqlalchemy.org/en/20/tutorial/data_update.html
https://datatofish.com/update-records-sql-server/
https://www.dev2qa.com/how-to-use-python-to-insert-delete-update-query-data-in-sqlite-db-table/
https://kontext.tech/article/893/call-sql-server-procedure-in-python
https://learn.microsoft.com/en-us/sql/connect/python/pymssql/python-sql-driver-pymssql?view=sql-server-ver16
https://pythontic.com/database/mysql/stored_procedure
https://github.com/pymssql/pymssql/blob/master/tests/test_connections.py
https://pynative.com/python-mysql-execute-stored-procedure/

"""

import sys
import os
import pymssql
import pymysql
import pyodbc
import BookKind

class sqlDAL(object):

    def mysqlconnect():
        """
        连接MySQL 检测其版本
        """
        # To connect MySQL database
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password="geovindu",
            db='geovindu',
        )

        cur = conn.cursor()
        cur.execute("select @@version")
        output = cur.fetchall()
        print(output)

        # To close the connection
        cur.close()
        conn.close()

    def connectDB(self, host, user, psw, db_name, charset='utf8'):
        self.db = pymysql.connect(host=host, user=user, password=psw, db=db_name, charset=charset)


    def execSql(self, sql):
        """
        执行SQL语句
        :param sql: SQL 语句
        :return:
        """
        # sql is insert, delete or update statement
        cursor = self.db.cursor()
        try:
            cursor.execute(sql)
            # commit sql to mysql
            self.db.commit()
            cursor.close()
            return True
        except:
            self.db.rollback()
        return False


    def select():
        """
        查询
        """
        # To connect MySQL database
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password="770214",
            db='geovindu',
        )

        cursor = conn.cursor()
        cursor.callproc('proc_Select_BookKindListAll')
        # print results
        print("Printing laptop details")
        #for result in cursor.stored_results():
            #print(result.fetchall())
        rows = cursor.fetchall()
        for row in rows:
            print(f'{row[0]} {row[1]} {row[2]}')
        # To close the connection
        cursor.close()
        conn.close()


    def selectdu():
        """
        查询
        """
        # To connect MySQL database
        conn = pymysql.connect(
            host='localhost',
            user='root',
            password="770214",
            db='geovindu',
        )

        cursor = conn.cursor()
        cursor.callproc('proc_Select_BookKindListAll')
        # print results
        print("Printing laptop details")
        #for result in cursor.stored_results():
        details =cursor.fetchall()#cursor.stored_results()#result.fetchall()
        for det in details:
            print(det)
        # To close the connection
        cursor.close()
        conn.close()


    def Add(objdu):
        """
        添加
        :param objdu: 书目录类
        :return:
        """
        # To connect MySQL database
        conn = pymysql.connect(
             host='localhost',
             user='root',
             password="770214",
             db='geovindu',
        )
        #print(type(objdu.getBookKindName()),objdu.getBookKindParent())
        cursor = conn.cursor() #prepared=True
        args=(objdu.getBookKindName(), objdu.getBookKindParent())
        cursor.callproc('proc_Insert_BookKindList', args)
        conn.commit()
        # print results
        print("Printing laptop details")
        #for result in cursor.stored_results():
            #print(result.fetchall())
            # To close the connection
        cursor.close()
        conn.close()

    def Addstr(BookKindID, BookKindName, BookKindParent):
        """
        添加
        :param BookKindName:
        :param BookKindParent:
        :return:
        """
        # To connect MySQL database
        conn = pymysql.connect(
             host='localhost',
             user='root',
             password="770214",
             db='geovindu',
        )

        cursor = conn.cursor()#prepared=True
        args = (BookKindName, BookKindParent)
        cursor.callproc('proc_Insert_BookKindList', args)
        conn.commit()
        # print results
        print("Printing laptop details")
        #for result in cursor.stored_results():
            #print(result.fetchall())
            # To close the connection
        cursor.close()
        conn.close()

  

 

调用:

import MySQLDAL
import BookKind

  MySQLDAL.sqlDAL.mysqlconnect()
    #MySQLDAL.sqlDAL.Addstr(0,"文学",1)
    tu.append(BookKind.BookKindList(0,"科学",1))

    MySQLDAL.sqlDAL.Add(BookKind.BookKindList(0,"科学",1))
    MySQLDAL.sqlDAL.select()
    MySQLDAL.sqlDAL.selectdu()

  

 输出:

(('8.0.32',),)
<class 'str'> 1
Printing laptop details
Printing laptop details
1 六福书目录 0
6 文学 1
7 科学 1
Printing laptop details
(1, '六福书目录', 0)
(6, '文学', 1)
(7, '科学', 1)

  

标签:BookKindName,BookKindParent,python,self,geovindu,cursor,read,BookKindList,mysql
From: https://www.cnblogs.com/geovindu/p/17484311.html

相关文章

  • MySQL的执行顺序
    学习java后端离不开MySQL,但是对于一条SQL语句,是如何执行,以及最终返回结果的生成一直有点黑盒,本次梳理了MySQL的执行过程,顺便弄清了一直没懂的Innodb中索引下推优化的过程。一条SQL语句的执行大概分为六个部分初始语句-->语法和词法解析-->语义解析-->进行查询优化,生成执行......
  • python下载文件的N中方式
    今天我们一起学习如何使用不同的Python模块从web下载文件。此外,你将下载常规文件、web页面、AmazonS3和其他资源。最后,你将学习如何克服可能遇到的各种挑战,例如下载重定向的文件、下载大型文件、完成一个多线程下载以及其他策略。1、使用requests你可以使用requests模块从一个......
  • Python之pandas基础
    1.pandas简介:paneldataanalysis(多维数据分析)pandas中具有两种基本的数据存储结构,存储一维values的Series和存储二维values的DataFrame;Series:Series一般由四个部分组成,分别是序列的值data、索引index、存储类型dtype、序列的名字name。其中,索引也可以指......
  • 【python基础】函数-参数形式
    鉴于函数定义中可能包含多个形参变量,因此函数调用中也可能包含多个实参变量。向函数传递实参变量给形参变量的方式有很多,可使用位置参数,这要求实参变量的顺序与形参变量的顺序相同;也可使用关键字参数,都由变量名和值组成,简称名称-值对;还可使用列表(元组)和字典。1.位置参数调用函数......
  • 在Python中根据字典值寻找键
    问题描述  在处理VOC数据集时,创建的字典如下所示label_map={0:'background',1:'aeroplane',2:'bicycle',3:'bird',4:'boat',5:'bottle',6:'bus',7:'car',8:'cat',9:......
  • SQL 之 DML(MySQL)
    插入数据若插入的列包含外键,需要确保外键的值在被应用的表里是存在的。插入指定列的数据insertinto表名[(列名1,..)]values(列值1,…)前提为省略的列名的属性为空。INSERTINTOEMP(EMPNO,ENAME)VALUES('7369','SMITH');插入所有列的数据insertinto表名values......
  • python: enforcing type check on function using decorator
     deftypeassert(*ty_args,**ty_kwargs):"""利用装饰器对函数参数强制性类型检查enforcingtypecheckonfunctionusingdecorator:paramty_args::paramty_kwargs::return:"""......
  • Python下载安装
    Python下载的官网:WelcometoPython.org      会出现四个python文件将这个拖到桌面查看Python是否安装好两种方式:1.IDLE编辑器 2.使用运行对话框下载PychamPycham官网:下载PyCharm:JetBrains为专业开发者提供的PythonIDE 安装成功首......
  • 通过python封装接口获取淘宝商品页面数据、淘宝商品详情数据
    可以使用GET或POST方法,请求参数中应包含商品详情页面数据、标题、价格、图片、库存、销量等信息。解析返回的response中的HTML页面或JSON格式数据,提取需要的商品信息,如商品标题、价格、评价人数等。使用pandas库将提取的商品信息保存到数据框中,以方便后续处理和分析。......
  • k8s实战案例之基于StatefulSet控制器运行MySQL一主多从
    1、前言Pod调度运⾏时,如果应⽤不需要任何稳定的标示、有序的部署、删除和扩展,则应该使⽤⼀组⽆状态副本的控制器来部署应⽤,例如Deployment或ReplicaSet更适合⽆状态服务需求,⽽StatefulSet适合管理所有有状态的服务,⽐如MySQL、MongoDB集群等。2、StatefulSet控制器运行MySQL一......