我正在使用 gin 框架并尝试使用 grom 进行 crud 操作。我正在尝试从 MYSQL 数据库中获取数据。我有 db.go 来获取数据库实例,每个表和模型的一些 Controller 我有一个这样的模型
type Campaigns struct {
ID int `json:"id" form:"id" gorm:"column:CampaignID"`
UserID int `json:"userId" form:"userId" gorm:"column:UserID"`
Name string `json:"name" form:"name" gorm:"column:Name"`
StartDate time.Time `json:"start" form:"start" gorm:"column:StartDate"`
EndDate time.Time `json:"end" form:"end" gorm:"column:EndDate"`
Customer string `json:"customer" form:"customer" gorm:"column:Customer"`
CustomerID int `json:"customerId" form:"customerId" gorm:"column:CustomerID"`
ImpressionsCounter int `json:"ImpressionsCounter" form:"ImpressionsCounter" gorm:"column:ImpressionsCounter"`
MaxImpressions int `json:"maxImpressions" form:"maxImpressions" gorm:"column:MaxImpressions"`
CurrentSpend float64 `json:"currentSpend" gorm:"column:CurrentSpend"`
MaxSpend float64 `json:"maxSpend" form:"maxSpend" gorm:"column:MaxSpend"`
Active bool `json:"active" form:"active" gorm:"column:Active"`
Created time.Time `json:"created" gorm:"column:DateCreated"`
Updated time.Time `json:"updated" gorm:"column:DateCreated"`
}
这是我正在使用的一个 Controller
package controllers
import (
"time"
"github.com/op/go-logging"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
"../models"
)
var log = logging.MustGetLogger("AsAPI")
type AsController struct {
DB gorm.DB
}
func (ac *AsController) SetDB(d gorm.DB) {
ac.DB = d
ac.DB.LogMode(true)
}
// Get all table
func (ac *AsController) ListTable(c *gin.Context) {
var results []models.Campaigns
err := ac.DB.Find(&results)
if err != nil {
log.Debugf("Error when looking up Table, the error is '%v'", err)
res := gin.H{
"status": "404",
"error": "No Table found",
}
c.JSON(404, res)
return
}
content := gin.H{
"status": "200",
"result": "Success",
"Table": results,
}
c.Writer.Header().Set("Content-Type", "application/json")
c.JSON(200, content)
}
获取数据库连接我正在使用
package controllers
import (
"time"
"github.com/op/go-logging"
"github.com/gin-gonic/gin"
"github.com/jinzhu/gorm"
_ "github.com/go-sql-driver/mysql"
"../models"
)
var log = logging.MustGetLogger("AdsAPI")
type AsController struct {
DB gorm.DB
}
func (ac *AsController) SetDB(d gorm.DB) {
ac.DB = d
ac.DB.LogMode(true)
}
我正在使用以下路线
ac := controllers.AdsController{}
ac.SetDB(dc.GetDB())
// Get a Ads resource
router := gin.Default()
router.GET("/table", ac.ListTables)
当我运行这个时,我得到以下错误
(/api/controllers/table.go:30)
[2016-03-23 09:56:39] [0.99ms] SELECT * FROM `tables`
2016/03/23 09:56:39 Error when looking up tables, the error is '&{0xc8202140e0 sql: Scan error on column index 3: unsupported driver -> Scan pair: []uint8 -> *time.Time 1 <nil> 0xc82022f860 0xc82022f7c0 0xc82021e140 2 {0xc8201fb4a0} <nil> false map[] map[]}'
[GIN] 2016/03/23 - 09:56:39 | 404 | 1.153811ms | 127.0.0.1 | GET /table
这个错误的原因是什么?帮我解决这个错误?
最佳答案
你可以在驱动文档中找到答案 https://github.com/go-sql-driver/mysql#timetime-support :
The default internal output type of MySQL DATE and DATETIME values is []byte which allows you to scan the value into a []byte, string or sql.RawBytes variable in your programm.
However, many want to scan MySQL DATE and DATETIME values into time.Time variables, which is the logical opposite in Go to DATE and DATETIME in MySQL. You can do that by changing the internal output type from []byte to time.Time with the DSN parameter parseTime=true. You can set the default time.Time location with the loc DSN parameter.
Alternatively you can use the NullTime type as the scan destination, which works with both time.Time and string / []byte.
关于mysql - 全选在 golaong gorm 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36170330/
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
在Rails4.0.2中,我使用s3_direct_upload和aws-sdkgems直接为s3存储桶上传文件。在开发环境中它工作正常,但在生产环境中它会抛出如下错误,ActionView::Template::Error(noimplicitconversionofnilintoString)在View中,create_cv_url,:id=>"s3_uploader",:key=>"cv_uploads/{unique_id}/${filename}",:key_starts_with=>"cv_uploads/",:callback_param=>"cv[direct_uplo
文章目录一、概述简介原理模块二、配置Mysql使用版本环境要求1.操作系统2.mysql要求三、配置canal-server离线下载在线下载上传解压修改配置单机配置集群配置分库分表配置1.修改全局配置2.实例配置垂直分库水平分库3.修改group-instance.xml4.启动监听四、配置canal-adapter1修改启动配置2配置映射文件3启动ES数据同步查询所有订阅同步数据同步开关启动4.验证五、配置canal-admin一、概述简介canal是Alibaba旗下的一款开源项目,Java开发。基于数据库增量日志解析,提供增量数据订阅&消费。Git地址:https://github.co
我目前正在尝试学习RubyonRails和测试框架RSpec。assigns在此RSpec测试中做什么?describe"GETindex"doit"assignsallmymodelas@mymodel"domymodel=Factory(:mymodel)get:indexassigns(:mymodels).shouldeq([mymodel])endend 最佳答案 assigns只是检查您在Controller中设置的实例变量的值。这里检查@mymodels。 关于ruby-o
我看到其他人也遇到过类似的问题,但没有一个解决方案对我有用。0.3.14gem与其他gem文件一起存在。我已经完全按照此处指示完成了所有操作:https://github.com/brianmario/mysql2.我仍然得到以下信息。我不知道为什么安装程序指示它找不到include目录,因为我已经检查过它存在。thread.h文件存在,但不在ruby目录中。相反,它在这里:C:\RailsInstaller\DevKit\lib\perl5\5.8\msys\CORE\我正在运行Windows7并尝试在Aptana3中构建我的Rails项目。我的Ruby是1.9.3。$gemin
我已经开始使用mysql2gem。我试图弄清楚一些基本的事情——其中之一是如何明确地执行事务(对于批处理操作,比如多个INSERT/UPDATE查询)。在旧的ruby-mysql中,这是我的方法:client=Mysql.real_connect(...)inserts=["INSERTINTO...","UPDATE..WHEREid=..",#etc]client.autocommit(false)inserts.eachdo|ins|beginclient.query(ins)rescue#handleerrorsorabortentirelyendendclient.commi
这段代码似乎创建了一个范围从a到z的数组,但我不明白*的作用。有人可以解释一下吗?[*"a".."z"] 最佳答案 它叫做splatoperator.SplattinganLvalueAmaximumofonelvaluemaybesplattedinwhichcaseitisassignedanArrayconsistingoftheremainingrvaluesthatlackcorrespondinglvalues.Iftherightmostlvalueissplattedthenitconsumesallrvaluesw
你能解释一下吗?我想评估来自两个不同来源的值和计算。一个消息来源为我提供了以下信息(以编程方式):'a=2'第二个来源给了我这个表达式来评估:'a+3'这个有效:a=2eval'a+3'这也有效:eval'a=2;a+3'但我真正需要的是这个,但它不起作用:eval'a=2'eval'a+3'我想了解其中的区别,以及如何使最后一个选项起作用。感谢您的帮助。 最佳答案 您可以创建一个Binding,并将相同的绑定(bind)与每个eval相关联调用:1.9.3p194:008>b=binding=>#1.9.3p194:009>eva
我无法运行Spring。这是错误日志。myid-no-MacBook-Pro:myid$spring/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/lib/spring/sid.rb:17:in`fiddle_func':uninitializedconstantSpring::SID::DL(NameError)from/Users/myid/.rbenv/versions/1.9.3-p484/lib/ruby/gems/1.9.1/gems/spring-0.0.10/li
我在RoR应用程序中有一个提交表单,是使用simple_form构建的。当字段为空白时,应用程序仍会继续下一步,而不会提示错误或警告。默认情况下,这些字段应该是required:true;但即使手动编写也行不通。该应用有3个步骤:NewPost(新View)->Preview(创建View)->Post。我的Controller和View的摘录会更清楚:defnew@post=Post.newenddefcreate@post=Post.new(params.require(:post).permit(:title,:category_id))ifparams[:previewButt