碰巧我有一个名为 Hana (Hana DB) 的数据库连接,使用编程语言 Go (Golang)。使用 Iris 框架。
发生的事情是 Go 在空数据方面存在问题。您必须在结构中使用特殊数据类型(使用安装 Go 时默认提供的 sql 库)sql.NullString
问题是,当连接到某个 URL 并返回一个 JSON 时,我有一个 GetEmployeeData () 函数被调用。问题是它不返回任何内容,出现 CONNECTION error REJECTED 并在控制台中打印错误: hdb.protocol 2018/07/13 16:31:06 option.go:120: 类型代码 tcNull 未实现退出状态 1 该代码已经在另一个函数的另一个 SQL 调用中进行了测试并且它可以工作,但是我认为这个 SQL 只返回 1 Null 或更多时它会出错。
代码如下:
func GetEmployeeData(ctx iris.Context) {
const (
driverName = "hdb"
hdbDsn = "hdb://SYSTEM:manager@62.28.253.218:30015"
)
//db, err := sql.Open(driverName, hdbDsn)
//Crea una abstraccion de conexion a base de datos pero no conecta
//Si no que prepara todo para la conexion
db, err := sql.Open(driverName, hdbDsn)
if err != nil {
log.Fatal(err)
}
//Declaramos variable de QUERY
//var peticion = GetCompanyData()
//fmt.Println(peticion)
// var companyData = GetCompanyData()
var request = `Select
"U_idcodigo",
"U_idapenom",
"U_idnumint",
"U_ctestado",
"U_idemail",
"U_cttipfun",
"U_uocodcar",
TO_CHAR("U_uocarasi",'dd/mm/yyyy'),
"U_uocodfun",
TO_CHAR("U_uofunasi",'dd/mm/yyyy'),
"U_idestciv",
"U_idsexo",
"U_idnacion",
"U_codcat",
"U_codesp",
TO_CHAR("U_idfecnac",'dd/mm/yyyy'),
"U_idfotogr",
"U_dodirecc","
U_docodpai",
"U_doregion",
"U_doprovin",
"U_docomuna",
"U_docodpos",
"U_donummov",
"U_cttipcon",
TO_CHAR("U_ctfecing",'dd/mm/yyyy'),
"U_uolugpag",
"U_uolugtra",
"U_uocodger",
"U_uocoddep",
"U_uocodsec",
"U_rpforpag",
"U_rpcodban",
"U_rpctacte",
"U_rptipocta",
"U_rpunisal",
"U_rpmoneda",
TO_VARCHAR("U_rpsalar"),
"U_tijor",
TO_VARCHAR("U_hdia"),
TO_VARCHAR("U_cthorcon"),
"U_sindi",
"U_jubil",
"U_turno",
TO_CHAR("U_turnoasi",'dd/mm/yyyy'),
"U_comentar"
FROM SBODemoCL."@A1A_MAFU"
Where "U_idcodigo" = '7579684-6'`
rows, err := db.Query(request)
if err != nil {
log.Fatal(err)
fmt.Println("No funciono la peticion")
}
defer rows.Close()
defer db.Close()
fmt.Println("Funciono la peticion")
type Employee struct {
CodigoEmpleado sql.NullString `json:"CodigoEmpleado"` //CODIGO UNICO DE EMPLEADO
Nombres sql.NullString `json:"Nombres"` //APELLIDO Y NOMBRE
NroInterno sql.NullString `json:"NroInterno"` //NUMERO INTERNO EN EMPRESA
Estado sql.NullString `json:"Estado"`
Email sql.NullString `json:"Email"` //CORREO ELECTRONICO
TipoF sql.NullString `json:"TipoF"` //TIPO DE FUNCIONARIO
Cargo sql.NullString `json:"Cargo"` //EL CARGO QUE OCUPA EL EMPLEADO
FechaCargo sql.NullString `json:"FechaCargo"` //FECHA DE ASIGNACION DE CARGO
Funcion sql.NullString `json:"Funcion"` //QUE FUNCION CUMPLE
FechaFuncion sql.NullString `json:"FechaFuncion"` //CUANDO SE LE ASIGNO SU FUNCION
Civil sql.NullString `json:"Civil"` //ESTADO CIVIL
Sexo sql.NullString `json:"Sexo"` //SI ES MASCULINO O FEMENINO
Nacionalidad sql.NullString `json:"Nacionalidad"` //SU NACIONALIDAD
Categoría sql.NullString `json:"Categoría"` //SU CATEGORIA
Especialidad sql.NullString `json:"Especialidad"` //SU ESPECIALIDAD
Nacimiento sql.NullString `json:"Nacimiento"` //FECHA DE NACIMIENTO
Fotografia sql.NullString `json:"Fotografia"` //RUTA DE MAPA DE BITS DE IMAGEN SOBRE EL EMPLEADO
Direccion sql.NullString `json:"Direccion"` //DIRECCION DE CASA DEL EMPLEADO
Pais sql.NullString `json:"Pais"` //PAIS EN DONDE SE ENCUENTRA ACTUALMENTE
Region sql.NullString `json:"Region"` //REGION DONDE SE ENCUENTRA ACTUALMENTE
Provincia sql.NullString `json:"Provincia"` //PROVINCIA DONDE SE ENCUENTRA ACTUALMENTE
Comuna sql.NullString `json:"Comuna"` //COMUNA DONDE SE ENCUENTRA ACTUALMENTE
C_Postal sql.NullString `json:"C_Postal"` //SU CODIGO POSTAL
Celular sql.NullString `json:"Celular"` //NUMERO DE CELULAR
TipoContrato sql.NullString `json:"TipoContrato"` //TIPO DE CONTRATO
FechaIngreso sql.NullString `json:"FechaIngreso"` //FECHA DE INGRESO A LA COMPAÑIA
LugarPago sql.NullString `json:"LugarPago"` //LUGAR DONDE NORMALMENTE COBRA EL EMPLEADO
LugarTrabajo sql.NullString `json:"LugarTrabajo"` //LUGAR DONDE NORMALMENTE TRABAJA EL EMPLEADO
Gerencia sql.NullString `json:"Gerencia"` //¿Quien es su genente? No es claro
Departamento sql.NullString `json:"Departamento"` //¿Si tiene departamento? ¿O la ubicacion de su departamento? ¿O con departamento se refieren a su partido o barrio?
Seccion sql.NullString `json:"Seccion"` //¿? Tampoco me queda claro
FormaPago sql.NullString `json:"FormaPago"` //COMO SE LE PAGA NORMALMENTE AL EMPLEADO
Banco sql.NullString `json:"Banco"` //EL BANCO QUE SE UTILIZA PARA DEPOSITAR EL SALARIO DEL EMPLEADO
CuentaBanco sql.NullString `json:"CuentaBanco"` //CUENTA BANCARIO DONDE SE DEPOSITA EL SALARIO
UnidadSalarial sql.NullString `json:"UnidadSalarial"` //¿? Su unidad salarial
Moneda sql.NullString `json:"Moneda"` //CON QUE TIPO DE MONEDA SE DEPOSITA SU SUELDO (EUROS, DOLARES, PESOS, ETC...)
Sueldo sql.NullString `json:"Sueldo"` //SUELDO BASICO DEL EMPLEADO
TipoJornada sql.NullString `json:"TipoJornada"` //TIPO DE JORNADA DEL EMPLEADO (CANTIDAD DE HORAS QUE TRABAJA)
HorasDia sql.NullString `json:"HorasDia"` //HORAS DIARIAS QUE ESTIPULA EL CONTRATO
HorasMes sql.NullString `json:"HorasMes"` //HORAS MENSUALES QUE ESTIPULA EL CONTRATO
Sindicato sql.NullString `json:"Sindicato"` //SINDICATO AL QUE PERTENECE EL EMPLEADO
Jubilido sql.NullString `json:"Jubilido"` //¿? Puede ser si es que esta jubilado o no
Turno sql.NullString `json:"Turno"` //¿Turno de que?
FechaTurno sql.NullString `json:"FechaTurno"` //FECHA EN QUE SE LE ASIGNO EL TURNO
Comentarios sql.NullString `json:"Comentarios"` //Comentarios sobre el empleado
}
// numero := 0
//
// ac := accounting.Accounting{
// Symbol: "", //El símbolo
// Precision: 2, // ¿Cuántos "centavos" queremos? (también llamado precisión)
// Thousand: companyData["ISeparator"], //Separador de miles
// Decimal: companyData["FSeparator"], //Separador de decimales
// }
employ := new(Employee)
for rows.Next() {
err := rows.Scan(
&employ.CodigoEmpleado,
&employ.Nombres,
&employ.NroInterno,
&employ.Estado,
&employ.Email,
&employ.TipoF,
&employ.Cargo,
&employ.FechaCargo,
&employ.Funcion,
&employ.FechaFuncion,
&employ.Civil,
&employ.Sexo,
&employ.Nacionalidad,
&employ.Categoría,
&employ.Especialidad,
&employ.Nacimiento,
&employ.Fotografia,
&employ.Direccion,
&employ.Pais,
&employ.Region,
&employ.Provincia,
&employ.Comuna,
&employ.C_Postal,
&employ.Celular,
&employ.TipoContrato,
&employ.FechaIngreso,
&employ.LugarPago,
&employ.LugarTrabajo,
&employ.Gerencia,
&employ.Departamento,
&employ.Seccion,
&employ.FormaPago,
&employ.Banco,
&employ.CuentaBanco,
&employ.UnidadSalarial,
&employ.Moneda,
&employ.Sueldo,
&employ.TipoJornada,
&employ.HorasDia,
&employ.HorasMes,
&employ.Sindicato,
&employ.Jubilido,
&employ.Turno,
&employ.FechaTurno,
&employ.Comentarios,
)
if err != nil {
log.Fatal(err)
}
// f, err := strconv.ParseFloat(valor6, 64)
// salario := ac.FormatMoney(f)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
fmt.Println("Ocurrio un error")
}
ctx.JSON(employ)
}
导入的库如下:
import (
"database/sql"
"fmt"
"log"
"strconv"
"github.com/kataras/iris"
"github.com/leekchan/accounting"
// Register hdb driver.
_ "github.com/SAP/go-hdb/driver"
)
错误调用了一个 option.go 文件。 go选项的全部代码如下:
/*
Copyright 2014 SAP SE
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package protocol
import (
"fmt"
"github.com/SAP/go-hdb/internal/bufio"
)
type booleanType bool
func (t booleanType) String() string {
return fmt.Sprintf("%t", t)
}
type intType int32
func (t intType) String() string {
return fmt.Sprintf("%d", t)
}
type bigintType int64
func (t bigintType) String() string {
return fmt.Sprintf("%d", t)
}
type doubleType float64
func (t doubleType) String() string {
return fmt.Sprintf("%g", t)
}
type stringType []byte
type binaryStringType []byte
func (t binaryStringType) String() string {
return fmt.Sprintf("%v", []byte(t))
}
//multi line options (number of lines in part header argumentCount)
type multiLineOptions []plainOptions
func (o multiLineOptions) size() int {
size := 0
for _, m := range o {
size += m.size()
}
return size
}
//pointer: append multiLineOptions itself
func (o *multiLineOptions) read(rd *bufio.Reader, lineCnt int) {
for i := 0; i < lineCnt; i++ {
m := plainOptions{}
cnt := rd.ReadInt16()
m.read(rd, int(cnt))
*o = append(*o, m)
}
}
func (o multiLineOptions) write(wr *bufio.Writer) {
for _, m := range o {
wr.WriteInt16(int16(len(m)))
m.write(wr)
}
}
type plainOptions map[int8]interface{}
func (o plainOptions) size() int {
size := 2 * len(o) //option + type
for _, v := range o {
switch v := v.(type) {
default:
outLogger.Fatalf("type %T not implemented", v)
case booleanType:
size++
case intType:
size += 4
case bigintType:
size += 8
case doubleType:
size += 8
case stringType:
size += (2 + len(v)) //length int16 + string length
case binaryStringType:
size += (2 + len(v)) //length int16 + string length
}
}
return size
}
func (o plainOptions) read(rd *bufio.Reader, cnt int) {
for i := 0; i < cnt; i++ {
k := rd.ReadInt8()
tc := rd.ReadB()
switch TypeCode(tc) {
default:
outLogger.Fatalf("type code %s not implemented", TypeCode(tc))
case tcBoolean:
o[k] = booleanType(rd.ReadBool())
case tcInteger:
o[k] = intType(rd.ReadInt32())
case tcBigint:
o[k] = bigintType(rd.ReadInt64())
case tcDouble:
o[k] = doubleType(rd.ReadFloat64())
case tcString:
size := rd.ReadInt16()
v := make([]byte, size)
rd.ReadFull(v)
o[k] = stringType(v)
case tcBstring:
size := rd.ReadInt16()
v := make([]byte, size)
rd.ReadFull(v)
o[k] = binaryStringType(v)
}
}
}
func (o plainOptions) write(wr *bufio.Writer) {
for k, v := range o {
wr.WriteInt8(k)
switch v := v.(type) {
default:
outLogger.Fatalf("type %T not implemented", v)
case booleanType:
wr.WriteInt8(int8(tcBoolean))
wr.WriteBool(bool(v))
case intType:
wr.WriteInt8(int8(tcInteger))
wr.WriteInt32(int32(v))
case bigintType:
wr.WriteInt8(int8(tcBigint))
wr.WriteInt64(int64(v))
case doubleType:
wr.WriteInt8(int8(tcDouble))
wr.WriteFloat64(float64(v))
case stringType:
wr.WriteInt8(int8(tcString))
wr.WriteInt16(int16(len(v)))
wr.Write(v)
case binaryStringType:
wr.WriteInt8(int8(tcBstring))
wr.WriteInt16(int16(len(v)))
wr.Write(v)
}
}
}
如果有人想在他们的 Go 文件夹中下载库,这是命令:
去获取 github.com/SAP/go-hdb/driver
这是您的 Github 链接:https://github.com/SAP/go-hdb
有谁知道如何解决这个错误?
最佳答案
您的错误是提示“我不知道如何读取空值。”
options.go 文件的读取函数在第 117 行有一个 switch 语句,它实现了读取各种数据库类型的方法。您需要更新此 switch 语句才能处理空(“tcNull”?)类型值。
关于sql - 错误 tcNull Golang HanadB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51333875/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa
这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]
尝试在我的RoR应用程序中实现计数器缓存列时出现错误Unknownkey(s):counter_cache。我在这个问题中实现了模型关联:Modelassociationquestion这是我的迁移:classAddVideoVotesCountToVideos0Video.reset_column_informationVideo.find(:all).eachdo|p|p.update_attributes:videos_votes_count,p.video_votes.lengthendenddefself.downremove_column:videos,:video_vot