我正在编写一个AWS lambda,以使用Golang SDK从RDS(SQL Server)查询10个不同的表。到目前为止,我了解到的是我们必须为该表创建一个类似的结构以对其进行查询。但是,由于我要查询10个表,所以我不想为每个表创建结构,即使表架构有一天可能会更改。
最近,我想为每个表创建一个CSV文件作为包含查询数据的备份,并将其上传到S3。那么是否可以将CSV文件直接导入到lambda中,以便我可以直接将其上传到S3?您可以在下面看到我当前的代码
func executeQuery(dbconnection *sql.DB) { println("\n\n----------Executing Query ----------") query := "select TOP 5 City,State,Country from IMBookingApp.dbo.Address" rows, err := dbconnection.Query(query) if err != nil { fmt.Println("Error:") log.Fatal(err) } println("rows", rows) defer rows.Close() count := 0 for rows.Next() { var City, State, Country string rows.Columns err := rows.Scan(&City, &State, &Country) if err != nil { fmt.Println("Error reading rows: " + err.Error()) } fmt.Printf("City: %s, State: %s, Country: %s\n", City, State, Country) count++ } }
此代码仅适用于Address表,不适用于其他表
Address
我也尝试过GORM
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mssql" ) type Currency struct { CurrencyId int `gorm:"column:CurrencyId;"` Code string `gorm:"column:Code;"` Description string `gorm:"column:Description;"` } func main() { db, err := gorm.Open("mssql", "sqlserver://***") db.SingularTable(true) gorm.DefaultTableNameHandler = func(dbVeiculosGorm *gorm.DB, defaultTableName string) string { return "IMBookingApp.dbo.Currency" } fmt.Println("HasTable-Currency:", db.HasTable("ClientUser")) var currency Currency db.Debug().Find(¤cy) fmt.Println("Currency:", currency) fmt.Println("Error", err) defer db.Close() }
通过这两种方法,我找不到使通用代码适用于多个表的任何方法。如果有人可以给我一些建议或您可以指出一些资源,我将不胜感激。
下面的代码为我工作-
conn, _ := getConnection() // Get database connection rows, err := conn.Query(query) if err != nil { fmt.Println("Error:") log.Fatal(err) } defer rows.Close() columns, err := rows.Columns() if err != nil { panic(err) } for rows.Next() { receiver := make([]string, len(columns)) is := make([]interface{}, len(receiver)) for i := range is { is[i] = &receiver[i] // each is[i] will be of type interface{} - compatible with Scan() // using the underlying concrete `*string` values from `receiver` } err := rows.Scan(is...) if err != nil { fmt.Println("Error reading rows: " + err.Error()) } fmt.Println("receiver", receiver)