S
S
Sergey2017-08-17 01:57:53
go
Sergey, 2017-08-17 01:57:53

Doesn't return value from PostgreSQL DB Go lang?

if you set an argument through a variable in the request, an error

package main

import (
  "fmt"  ///пакет стандартной библиотеки   Базовый пакет для форматирования функций ввода
  "time"  ///пакет для аботы со временем
  "database/sql"  ///пакет для работы с БД
  _ "github.com/lib/pq" //пакет для работы с БД
)


////указываю постоянные значения подключения к БД и сокету FreeSWITCH
const (
  DB_HOST		    = "127.0.0.1"
  DB_USER    	    = "postgres"
  DB_PASSWORD 	    = "postgres"
  DB_NAME     	    = "freeswitch"
)

////обьявляю глобальные переменные
var (
  err error
  id int
  client int
  id_dispach int
  db *sql.DB
)

func sql_req()  {
  rows, err := db.Query("SELECT client,id FROM  dialer_golang WHERE state = 'called' ORDER BY RANDOM() LIMIT 1")
  if err != nil {fmt.Println(err)}
  defer rows.Close()
  for rows.Next() {
    rows.Scan(&client, &id)  ///декодирую элементы которые хочу получить в БД
    dialer_rows , err := db.Query("SELECT  id_dispatch FROM dialer_golang WHERE client =  '$1' and state = 'called'",client)
    if err != nil {fmt.Println(err)
      return
    }
    defer dialer_rows.Close()  ///закрываем коннект к Базе данных
    for dialer_rows.Next() {
      dialer_rows.Scan(&id_dispach)
    }
    fmt.Println("ID Клиента",id,"Номер клиента",client,"DISPACH",id_dispach)
  }
}

func main()  {
  today := time.Now().Weekday()
  fmt.Println(today)
  time.Sleep(300 * time.Millisecond)   ///команда задержки sleep
  fmt.Println(today)

  // подключение к  Базе данных
  db_property := "host=" + DB_HOST + " user=" + DB_USER + " password=" + DB_PASSWORD + " dbname=" + DB_NAME + " sslmode=disable"
  db, err = sql.Open("postgres", db_property)
  err = db.Ping()
  if err != nil {fmt.Println("Error: IS NOT Connect  for  " + DB_NAME + " Host: " + DB_HOST)} else {fmt.Println("Database " + DB_NAME + " Host: " + DB_HOST + " Connect is GOOD")} ///проверка на ошибку если вернет ошибку то  выведет то что коннекта к бд нет
  defer db.Close() ///закрываем коннект к Базе данных
  sql_req()

}

If you specify how
dialer_rows , err := db.Query("SELECT  id_dispatch FROM dialer_golang WHERE client =  '$1' and state = 'called'",client)
Выводит 
[[email protected] script]# go run daemon.go
Database freeswitch Host: 127.0.0.1 Connect is GOOD
pq: got 1 parameters but the statement requires 0

Если задать как
dialer_rows , err := db.Query("SELECT  id_dispatch FROM dialer_golang WHERE client =  '79095876084' and state = 'called'")
Выводит 

Database freeswitch Host: 127.0.0.1 Connect is GOOD
ID Клиента 1 Номер клиента 79095876084 DISPACH 6582

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Alexey, 2017-08-17
@Kle6800

'$1' is treated as a string value.
Need this
WHERE client = $1 and state = 'called'",client)

A
Alexander Pavlyuk, 2017-08-17
@pav5000

https://golang.org/pkg/database/sql/#DB.Query
Judging by the documentation, the placeholder for inserting a parameter is a question mark, not "$1"
See the example there.

rows, err := db.Query("SELECT name FROM users WHERE age=?", age)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question