英文:
Is there a way to get the Type for a Column using package database/sql in golang?
问题
基本上,不事先知道查询结果结构的情况下,我想查询数据库并返回一个类似这样的结构(json-y)
// 行
[
// 行1
[
{ ColumnName: "id", Value: 1, Type: int },
{ ColumnName: "name", Value: "batman", Type: string },
...
],
// 行2
[
{ ColumnName: "id", Value: 2, Type: int },
{ ColumnName: "name", Value: "superman", Type: string },
...
]
]
在golang的database/sql包中,有没有一种方法可以获取列的类型?
我怀疑我想要做的是:
- 创建一个与列数量相同的interface{}数组,
- 然后对每一列确定其类型,
- 然后用指向该类型的指针填充数组,
- 然后将数组传递给Scan()函数。
这有点像sqlx中的这个代码示例,但不需要事先知道数据将填充的结构。
英文:
Basically, without knowing before hand what the resulting structure of a query might be, I'd like to query the database, and return a structure like this (json-y)
// Rows
[
// Row 1
[
{ ColumnName: "id", Value: 1, Type: int },
{ ColumnName: "name", Value: "batman", Type: string },
...
],
// Row 2
[
{ ColumnName: "id", Value: 2, Type: int },
{ ColumnName: "name", Value: "superman", Type: string },
...
]
]
Is there a way to get the Type for a Column using package database/sql in golang?
I'm suspecting that what I want to do is
- make an array of interface{} the size of Column(),
- then for each column determine it's type,
- then fill the array with a pointer to that type,
- and then pass the array to Scan()
Which is a little like this code example from sqlx, but without first knowing the Struct that the data would be populating.
答案1
得分: 6
你应该可以这样做:
func printRows(rows *sql.Rows){
colTypes, err := rows.ColumnTypes()
for _,s := range colTypes {
log.Println("cols type:", s.DatabaseTypeName());
}
}
英文:
You should be able to do it this way:
func printRows(rows *sql.Rows){
colTypes, err := rows.ColumnTypes()
for _,s := range colTypes {
log.Println("cols type:", s.DatabaseTypeName());
}
}
答案2
得分: 0
使用database/sql吗?不是(据我所知)。
但是你可以使用这段代码来进行任意查询。而json包中的json.Marshall()
函数会使用反射来确定正确的打印值的方式,所以你可以有一个像这样的结构:
type Column struct {
ColumnName string
ColumnValue interface{}
ColumnType string
}
然后使用reflect.TypeOf(someVariable).String()
来获取ColumnType的类型。
英文:
Using database/sql? No (as far as I know).
But you can use this code for arbitrary queries. And json.Marshall()
from the json package will use reflection to determine the right way to print a value, so you could have a structure like this:
type Column struct {
ColumnName string
ColumnValue interface{}
ColumnType string
}
And then use reflect.TypeOf(someVariable).String()
to get the type for ColumnType.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论