我在Go中编写了一种类似REST的API。我拥有的数据库是遗留的,因此我无法控制字段名称或结构或任何事情。我在一个名为datastore的独立包中抽象数据库访问方法。我的代码看起来像这样(跳过所有错误处理等)。
type Datastore struct {} type Object struct { id uint name string ... zillion more fields here } func (Datastore) ObjectList() { var objects *[]Object db, _ := sqlx.Open("postgres", conn_info) rows, _ := sqlx.Queryx("SELECT * FROM object_table") defer rows.Close() for rows.Next() { var obj Object rows.Scan(&obj.id, &obj.name) objects = append(objects, obj) } return objects }
我目前遇到的问题是对象表有几十个字段。有些我关心,但有些我不关心。有些名称与Object相同,有些则不是。最终,我需要支持其中的大多数,但我首先要进行概念验证。如果扫描代码在行中找到的字段多于Scan()参数中的字段,则扫描代码似乎失败。我可以在查询select id, name from object_table
中列出我扫描的字段,但是
1.它使代码非常难看(SQL没有通过gofmt格式化)
2.当我想支持另一个字段时,它会添加我需要编辑的另一个地方
有没有办法实现一个自定义扫描程序接口,该接口将获取行对象,将一些数据加载到结构中并忽略其余部分?
答案 0 :(得分:0)
您已经在使用sqlx,所以在查询之前只需使用* DB.Unsafe():
<div id="feather-prods" class="row">
<div id="div1">
<div id="prod-stop" class="col-md-5 col-sm-6 col-xs-8 col-xs-push-2 col-sm-push-1 col-md-push-1">
<div class="prod-img"><img id="tab1show" class="tab-content bigImg" src="images/broom/monara-pp-1.jpg" alt="feather, Purple monara broom"></div>
<div class="thumbnailImg">
<div id="tab1show" class="tab-content thumb"><img src="images/broom/monara-pp-1.jpg" alt="feather, Purple monara broom" border="0" width="100%" class="thumbImg" /></div>
<div id="tab1show" class="tab-content thumb"><img src="images/broom/monara-pp-2.jpg" alt="feather, Purple monara broom" border="0" width="100%" class="thumbImg" /></div>
<div id="tab1show" class="tab-content thumb"><img src="images/broom/monara-pp-3.jpg" alt="feather, Purple monara broom" border="0" width="100%" class="thumbImg" /></div>
<div id="tab1show" class="tab-content thumb"><img src="images/broom/monara-pp-4.jpg" alt="feather, Purple monara broom" border="0" width="100%" class="thumbImg" /></div>
</div>
</div>
</div>
<div id="div2" style="display:none;" >
<div id="prod-stop" class="col-md-5 col-sm-6 col-xs-8 col-xs-push-2 col-sm-push-1 col-md-push-1">
<div class="prod-img"><img id="tab2show" class="tab-content bigImg" src="images/broom/monara-b-1.jpg" alt="feather, black monara broom"></div>
<div class="thumbnailImg">
<div id="tab2show" class="tab-content thumb"><img src="images/broom/monara-b-1.jpg" alt="feather, black monara broom" border="0" width="100%" class="thumbImg" /></div>
<div id="tab2show" class="tab-content thumb"><img src="images/broom/monara-b-2.jpg" alt="feather, black monara broom" border="0" width="100%" class="thumbImg" /></div>
<div id="tab2show" class="tab-content thumb"><img src="images/broom/monara-b-3.jpg" alt="feather, black monara broom" border="0" width="100%" class="thumbImg" /></div>
<div id="tab2show" class="tab-content thumb"><img src="images/broom/monara-b-4.jpg" alt="feather, black monara broom" border="0" width="100%" class="thumbImg" /></div>
</div>
</div><!-- prod images end -->
</div>
</div>