您的位置:首页 > 教程笔记 > 综合教程

从 MySQL/Go 表获取行数据

2024-02-24 18:50:05 综合教程 150

php小编小新在这篇文章中将向大家介绍如何从MySQL/Go表获取行数据。MySQL是一种流行的关系型数据库管理系统,而Go是一种强大的开发语言。在开发过程中,我们经常需要从数据库中获取数据并进行处理。本文将详细介绍如何使用Go语言连接MySQL数据库,并通过查询语句从表中获取行数据。无论您是初学者还是有经验的开发者,本文都将为您提供有用的指导和示例代码。让我们开始吧!

问题内容

首先它读取代码,以便您了解它的逻辑,当运行我捕获它的存储过程时,它会为我带来一个包含我必须返回的数据的表,列的名称确实会带来它对我来说,但列的数据没有给我带来任何东西,我无法创建模型,并且存储过程的响应有 n 个列,有 n 个不同的名称,但列的不同之处在于具有 int 数据和字符串数据,我需要您从列中捕获正确的数据,因为一切正常,但列中的数据却不起作用:

package controllers

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "net/http"

    "github/gin-gonic/gin"
)

type RequestData struct {
    FromData map[string]interface{} `json:"fromData"`
    Call     string                 `json:"Call"`
}

func HandleDatos(c *gin.Context) {
    var requestData RequestData

    if err := c.ShouldBindJSON(&requestData); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    fmt.Printf("Ejecutando procedimiento almacenado: CALL %s\n", requestData.Call)
    fmt.Printf("Parámetros: %v\n", requestData.FromData)

    var rows *sql.Rows
    var err error

    // Verifica si FromData contiene valores
    if len(requestData.FromData) > 0 {
        // Si hay valores en FromData, crea una consulta con parámetros
        query := "CALL " + requestData.Call + "("
        params := []interface{}{}
        for _, value := range requestData.FromData {
            query += "?, "
            params = append(params, value)
        }
        query = query[:len(query)-2] + ")"

        rows, err = db.Raw(query, params...).Rows()
    } else {
        // Si no hay valores en FromData, ejecuta el procedimiento almacenado sin parámetros
        rows, err = db.Raw("CALL " + requestData.Call).Rows()
    }

    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    defer rows.Close()

    // Convierte los resultados en un mapa
    result := make(map[string]interface{})
    columns, err := rows.Columns()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    fmt.Printf("Columnas: %v\n", columns) // Punto de impresión

    data := [][]interface{}{} // Almacena los datos de filas
    for rows.Next() {
        values := make([]interface{}, len(columns))
        for i := range columns {
            values[i] = new(interface{})
        }

        if err := rows.Scan(values...); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        fmt.Printf("Valores escaneados: %v\n", values) // Punto de impresión

        row := make(map[string]interface{})
        for i, col := range columns {
            val := *(values[i].(*interface{}))
            row[col] = val
        }

        fmt.Printf("Fila escaneada: %v\n", row) // Punto de impresión

        // Agrega esta fila al resultado
        data = append(data, values)
    }

    fmt.Printf("Datos finales: %v\n", data) // Punto de impresión

    if len(data) > 0 {
        result["columns"] = columns
        result["data"] = data
    } else {
        // Si no hay datos, establece un mensaje personalizado
        result["message"] = "Sin datos"
    }

    // Convierte el resultado en JSON y devuelve la respuesta
    responseJSON, err := json.Marshal(result)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, string(responseJSON))
}

这就是它返回给我的内容,其中显示“columns”:[“idPunto”,“nombre”]该部分没问题,但包含数据的行不是我所期望的:

解决方法

将行扫描到接口{}中不会自动将 SQL 类型转换为 Go 类型。相反,使用 ColumnTypes 方法将获取每列的数据类型,允许您动态分配正确的 Go 类型。 (以下内容未经测试,仅供参考。)例如

for i := range columns {
    // Use the column types to determine the appropriate scan type
    switch columnTypes[i].DatabaseTypeName() {
    case "INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT":
        scanArgs[i] = new(int64)
    default:
        scanArgs[i] = new(string)
    }

    values[i] = scanArgs[i]
}

在您的脚本中:

package controllers

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "net/http"

    "github/gin-gonic/gin"
)

type RequestData struct {
    FromData map[string]interface{} `json:"fromData"`
    Call     string                 `json:"Call"`
}

func HandleDatos(c *gin.Context) {
    var requestData RequestData

    if err := c.ShouldBindJSON(&requestData); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    fmt.Printf("Ejecutando procedimiento almacenado: CALL %s\n", requestData.Call)
    fmt.Printf("Parámetros: %v\n", requestData.FromData)

    var rows *sql.Rows
    var err error

    // Verifica si FromData contiene valores
    if len(requestData.FromData) > 0 {
        // Si hay valores en FromData, crea una consulta con parámetros
        query := "CALL " + requestData.Call + "("
        params := []interface{}{}
        for _, value := range requestData.FromData {
            query += "?, "
            params = append(params, value)
        }
        query = query[:len(query)-2] + ")"

        rows, err = db.Raw(query, params...).Rows()
    } else {
        // Si no hay valores en FromData, ejecuta el procedimiento almacenado sin parámetros
        rows, err = db.Raw("CALL " + requestData.Call).Rows()
    }

    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }
    defer rows.Close()

    // Convierte los resultados en un mapa
    result := make(map[string]interface{})
    columns, err := rows.Columns()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    fmt.Printf("Columnas: %v\n", columns) // Punto de impresión

    data := []map[string]interface{}{} // Almacena los datos de filas

    // Get the column types
    columnTypes, err := rows.ColumnTypes()
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    for rows.Next() {
        values := make([]interface{}, len(columns)
        scanArgs := make([]interface{}, len(columns))

        for i := range columns {
            // Use the column types to determine the appropriate scan type
            switch columnTypes[i].DatabaseTypeName() {
            case "INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT":
                scanArgs[i] = new(int64)
            default:
                scanArgs[i] = new(string)
            }

            values[i] = scanArgs[i]
        }

        if err := rows.Scan(values...); err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }

        fmt.Printf("Valores escaneados: %v\n", values) // Punto de impresión

        row := make(map[string]interface{})
        for i, col := range columns {
            // Cast the scanned values to the appropriate data types
            switch columnTypes[i].DatabaseTypeName() {
            case "INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT":
                row[col] = *(scanArgs[i].(*int64))
            default:
                row[col] = *(scanArgs[i].(*string))
            }
        }

        fmt.Printf("Fila escaneada: %v\n", row) // Punto de impresión

        // Agrega esta fila al resultado
        data = append(data, row)
    }

    fmt.Printf("Datos finales: %v\n", data) // Punto de impresión

    if len(data) > 0 {
        result["columns"] = columns
        result["data"] = data
    } else {
        // Si no hay datos, establece un mensaje personalizado
        result["message"] = "Sin datos"
    }

    // Convierte el resultado en JSON y devuelve la respuesta
    responseJSON, err := json.Marshal(result)
    if err != nil {
        c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, string(responseJSON))
}

nb:您应该能够针对可能遇到的其他数据类型扩展此逻辑。

相关推荐

  • PHP SPL 数据结构:数据管理的终极武器

    PHP SPL 数据结构:数据管理的终极武器

    php spl数据结构是php标准库中提供的一组数据结构和算法,被称为数据管理的终极武器。php小编新一将为您详细介绍spl数据结构的特点和用法,帮助您更好地利用这些强大的工具来管理和处理数据。无论是

    综合教程 2024-02-24 18:50:02 127
  • 各种响应式布局类型的优劣分析

    各种响应式布局类型的优劣分析

    理解各种响应式布局类型的优缺点,需要具体代码示例摘要:随着移动互联网的快速发展,响应式设计成为网页开发中的重要技术。本文将介绍几种常见的响应式布局类型,并通过具体的代码示例来理解它们的优缺点。一、固定

    综合教程 2024-02-24 18:49:57 189
  • 高效快速的Golang数据转换技巧

    高效快速的Golang数据转换技巧

    在软件开发中,数据的转换是一项常见的任务,特别是在处理复杂数据结构或不同数据类型的情况下。在Go语言中,也称为Golang,有许多快速高效的方法来处理数据转换,让开发人员可以轻松地在不同数据类型之间转

    综合教程 2024-02-24 18:49:48 131
  • Python数据分析:数据驱动成功之路

    Python数据分析:数据驱动成功之路

    python 数据分析涉及使用 Python 编程语言从各种数据源中收集、清理、探索、建模和可视化数据。它提供了强大的工具和库,例如 NumPy、pandas、Scikit-learn 和 Matpl

    综合教程 2024-02-24 18:49:43 48
  • Python数据库操作的实战指南:让数据库操作成为你的拿手好戏

    Python数据库操作的实战指南:让数据库操作成为你的拿手好戏

    在python中,可以使用pyMysql或psycopg2等第三方库连接数据库。以pymysql为例,连接数据库的代码如下:import pymysql# 创建连接对象conn = pymysql.c

    综合教程 2024-02-24 18:49:17 49