python+selenium利用records進行數據庫操作

class ConnectDb:
    """
    利用records連接數據庫
    """
    @staticmethod
    def connect(filepath=None) -> records.Database:
        """
        :param filepath: 配置文件
        :return: <Database open=True> 數據庫對象
        """
        if filepath is None:
            file = INIFILEPATH
        else:
            file = filepath
        host = Readini.getvalue("Database", "dbhost", file)
        port = Readini.getvalue("Database", "dbport", file)
        user = Readini.getvalue("Database", "dbusername", file)
        passwd = Readini.getvalue("Database", "dbpasswd", file)
        db = Readini.getvalue("Database", "dbname")
        db_url = 'mysql+pymysql://' + user + ':' + passwd + '@' + str(host) + ':' + str(port) + '/' + db
        # connect = records.Database('mysql+pymysql://用戶名:密碼@sqlURl:sql端號/庫名')
        connect = records.Database(db_url)

        return connect
        
        
def insert_run_record(self, project_name, device_sn, device_static, run_value):
    """
    插入數據
    :param project_name: 項目名稱,取config文件中的項目名稱,字段 PROJECTNAME
    :param device_sn: 設備號
    :param device_static: 設備狀態
    :param run_value: 運行內容
    """
    try:
        value = {
                 'device_sn': device_sn,
                 'device_static': device_static,
                 'run_value': run_value,
                 'create_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                 }

        connect.query(
            "insert into selenium_chanpin_znsd_runvalue(project_id, device_sn,device_static,run_value,create_time) "
            "values(:project_id," +
            "(SELECT project_id FROM selenium_project where project_name = '" + project_name + "')" +
            ",:device_static, :run_value, :create_time)", **value)
    except Exception as e:
        print("sql運行失敗" + str(e))
        
        

        
def select_run_value(self, device_sn) -> str:
    """
    通過設備編號查詢最新一條運行數據的內容
    :param device_sn: 設備sn
    :return: 運行內容
    """
    try:

        select_value_sql = "SELECT run_value FROM selenium_chanpin_znsd_runvalue where device_sn='" + device_sn + \
                           " 'ORDER BY create_time DESC limit 1"
        rows = connect.query(select_value_sql)
        return rows.first(as_ordereddict=True)["run_value"]
    except Exception as e:
        print("執行sql失敗" + str(e))

需要依賴包PyMySQL 和 records


利用records連接數據庫,需要安裝records插件,records.Database連接數據庫,返回Database對象,主要用到records.Database.query來進行插入數據,查詢數據等操作

插入數據只需要設置相應的字段值:value,在sql的insert中的values中用(:字段值)來直接讀取相應的value,當sql語句中存在查詢其他表獲得的值時,需要在sql中拼接相應的select,如上所示。



查詢語句,拼接好sql好,執行connect.query(sql) 返回<RecordCollection size=0 pending=True>類的對象,該對象有三個常用的方法all/first/one,這三個方法都可以添加參數as_dict=True(將結果轉化爲字典) as_ordereddict=True(結果轉化爲字典並進行排序),其中all是返回所有的,first是第一個結果,one是唯一一個

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章