can't connect to postgresql database "database doesn´t exist" - database

I have a Go app that connects with a postgres database through the driver called "github.com/lib/pq".
I make a connection with a database called godb, and the function Open() works correctly, but when I check errors with db.Ping(), it tells me the database doesn´t exist, although I have created it in pg Admin and the name and the password are well written. I have tried to check if the connection string is correct, I have tried to create a new database and connect it but it gives the same error. I have also tried to disconnect and reconnect the database and it doesn't work.
package main
import (
"database/sql"
"fmt"
"log"
"sync"
//driver of the database
_ "github.com/lib/pq"
)
var (
db *sql.DB
once sync.Once
)
func NewPostgresDB() {
once.Do(func() {
var err error
db, err = sql.Open("postgres",
"postgres://postgres:/*password of the database*/#localhost:5432/godb?sslmode=disable")
if err != nil {
log.Fatalf("There is an error in the connction string %v", err)
}
if err = db.Ping(); err != nil {
log.Fatalf("There was an error connecting to the database %v", err)
}
})
fmt.Println("connection succeeded")
}
this is the error it exactly returns (it's in Spanish):
pq: no existe la base de datos �godb�
exit status 1

Related

sql statement.exec error: mssql: Incorrect syntax near '?'

I need help understanding this error. The code works with sqlite. The ? looks like the sql package is not even putting a value there but sending the question mark as is.
I can run other select statements without issues so its not a connection problem or something like that.
Error: Incorrect syntax near '?'
func TestSQLServerInsert(t *testing.T) {
db, err := sql.Open("sqlserver", "my_trusted_string")
//db, err := sql.Open("sqlite3", "../data/utm_info.db")
if err != nil {
t.Errorf("could not open database: %v", err)
}
defer db.Close()
c := controller.NewC(db)
u := controller.UtilizationResponse{
Snapshot: []int{46, 22, 4, 4, 5, 3, 0, 8, 49},
History: []float32{55.1, 47.2, 0.3, 33.4, 23.5},
Time: time.Now(),
}
affectedRows, err := c.InsertUtil(u)
if err != nil {
t.Errorf("could not insert into db: %v", err)
}
var count int64 = 1
assert.Equal(t, affectedRows, count)
}
// InsertUtil response inserts a new record into the database
func (c *Controller) InsertUtil(u UtilizationResponse) (rowsAffected int64, err error) {
return insertUtil(c.DB, u)
}
func insertUtil(db *sql.DB, u UtilizationResponse) (int64, error) {
stmt, err := db.Prepare("INSERT INTO Utilization VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
if err != nil {
return 0, err
}
res, err := stmt.Exec(
u.Time,
u.Snapshot[0],
u.Snapshot[1],
u.Snapshot[2],
u.Snapshot[3],
u.Snapshot[4],
u.Snapshot[5],
u.Snapshot[6],
u.Snapshot[7],
u.Snapshot[8],
u.History[0],
u.History[1],
u.History[2],
u.History[3],
u.History[4],
)
if err != nil {
return 0, err
}
rowCnt, err := res.RowsAffected()
if err != nil {
return 0, err
}
return rowCnt, nil
}
type UtilizationResponse struct {
Snapshot []int `json:"snapshot,omitempty"`
History []float32 `json:"history,omitempty"`
Time time.Time `json:"time,omitempty"`
}
The sqlserver driver uses normal MS SQL Server syntax and expects parameters in the sql query to be in the form of either #Name or #p1 to #pN (ordinal position).
insertSql := "insert into test (id, idstr) values (#p1, #p2)"
After some testing, I can confirm it works. It even works with sqlite3 so this seems to be a more widely accepted way.

Golang Unable to get instances from Sql Server Browser on host

I can't provide an Mssql connection. What's the problem?
Unable to get instances from Sql Server Browser on host DESKTOP-A:
read udp [8c32%vEthernet (Default Switch)]:55199->[8c32%vEthernet
(Default Switch)]:1434: i/o timeout
package main
import (
"database/sql"
"flag"
"fmt"
_ "github.com/denisenkom/go-mssqldb"
)
func main() {
var (
userid = flag.String("U", "loginx", "login_id")
password = flag.String("P", "1", "password")
server = flag.String("S", "DESKTOP-A\\SQLEXPRESS", "server_name[\\instance_name]")
database = flag.String("d", "test", "db_name")
)
flag.Parse()
dsn := "server=" + *server + ";user id=" + *userid + ";password=" + *password + ";database=" + *database
db, err := sql.Open("mssql", dsn)
if err != nil {
fmt.Println("Cannot connect: ", err.Error())
return
}
err = db.Ping()
if err != nil {
fmt.Println("Cannot connect: ", err.Error())
return
}
defer db.Close()
}
you can use sqlserver://user:pass#host:1433/instance?database=dbname as the DSN.
I'd like to point out that the default port the Go driver uses is 1434, which is the UDP port for SQLServer. However, in my experience, the server itself almost never uses that port by default. So by supplying the default TCP port, 1433, got it to work for me.

How add option `writeConcern` in mongo-go-driver?

I do not understand how to add recording parameters for MongoDB using mongo-go-driver
Example request
c.client.Database(MONGO_DATABASE).Collection(*packet.ID).InsertMany(nil, packet.Item, opt)
How to specify the necessary parameters in opt?
VERSION 1.0
In MongoDB Go driver production release you can set writeConcern as below:
import (
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
mongoURI := "mongodb://server:port/"
opts := options.Client().ApplyURI(mongoURI).SetWriteConcern(writeconcern.New(writeconcern.WMajority()))
client, err := mongo.NewClient(opts)
if err != nil {
panic(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
panic(err)
}
collection := client.Database("database").Collection("collection")
See also:
mongo-driver/mongo/options
mongo-driver/mongo/writeconcern
VERSION 0.0.16
Using mongo-go-driver, you can set a write concern option as below example:
import(
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/core/writeconcern"
"github.com/mongodb/mongo-go-driver/mongo"
"github.com/mongodb/mongo-go-driver/mongo/collectionopt"
)
// Example document
document := bson.VC.DocumentFromElements(
bson.EC.SubDocumentFromElements(
"foo",
bson.EC.Int32("bar", 101),
),
)
// Set majority write concern
wMajority := writeconcern.New(writeconcern.WMajority())
database := client.Database("database")
collection := database.Collection("collection", collectionopt.WriteConcern(wMajority))
_, err = collection.InsertOne(context.Background(), document)
Can also use W(int) to specify an arbitrary number of mongod instances. See more writeconcern/writeconcern.go

go-mssql set connection timeout

I'm having issues setting the timeout in go-mssqldb
This is my current connection string:
sqlserver://user:password#server?timeout=1m30s
I can connect just fine, run queries etc. but I keep timing out at the default value of 30 seconds.
I'm referencing the documentation here.
What am I missing?
import (
"database/sql"
_ "github.com/denisenkom/go-mssqldb"
)
func main(){
db, err := sql.Open("mssql", "sqlserver://user:password#server?timeout=1m30s")
if err != nil{
panic(err)
}
_, err = db.Exec("run query that takes longer than 30 seconds")
if err != nil{
panic(err)
}
// panic at 30 seconds...
// panic: read tcp {my ip}->{server ip}: i/o timeout
}
I was referencing the wrong documentation initially. To format the url see the following:
"sqlserver://user:password#server?connection+timeout=90"

Connecting to CloudSQL from App Engine (Second Generation CloudSQL) GO

Love the Stack, My first post out of complete frustration. Thanks for you comments!
Created App Engine Project
Created Second Generation MySQL Instance in my App Engine Project
Created Database in the MySQL Instance
In App Engine, I activate the --> Google Cloud Shell <--. ( I am working at a command prompt in my console.cloud.google.com)
I have copied this basic GO program to connect to my MySQL instance.
I build it and run it.
go build mysqlexample.go
./mysqlexample
I have not been able to achieve a successful connection. You can see all the various connection strings that I have tried and to the right of them is the response I get.
I can connect from my local windows machine using mysql admin.
Help?
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
)
func main() {
const dbIP = "104.xxx.xx.x"
const dbInstanceName = "esp-1-dev:us-central1:espdev"
const dbName = "servpro"
const dbUserName = "root"
const dbPassword = "xxxxxxx"
const dbOpenString = dbUserName + ":" + dbPassword + "#/" + dbInstanceName + "/" + dbName //GETS RESPONSE default addr for network 'AppEngine:Zone:Project' unknown
//const dbOpenString = dbUserName + "#cloudsql(" + dbInstanceName + ")/" + dbName //GETS RESPONSE dial cloudsql: unknown network cloudsql
//const dbOpenString = dbUserName + "#/" //+ "?parseTime=true&loc=UTC" //GETS RESPONSE getsockopt: connection refused
//const dbOpenString = dbUserName + ":" + dbPassword + "#tcp(" + dbIP + ":3306)/" + dbName //GETS RESPONSE dial tcp 104.xxx.xxx.x:3306: getsockopt: connection timed out
// Got this from stack overflow. GoDocs are not updated to reflect 2nd Gen databases.
// http://stackoverflow.com/questions/38890022/tls-requested-but-server-does-not-support-tls-error-with-google-cloud-sql-2nd
//user:password#cloudsql(copiedPastedInstanceConnectionName)/d‌​atabaseName?charset=‌​charset&collation=co‌​llation&tls=tlsConfi‌​gName&parseTime=true
//First Generation Connection String
//username:password#cloudsql(appID:CloudSQLInstance)/databasename?parseTime=true&loc=UTC
db, err := sql.Open("mysql", dbOpenString);
defer db.Close()
log.Println("Attempting Ping of database....")
err = db.Ping()
if err != nil {
log.Println("db.Ping() failed: " + dbOpenString)
log.Println(err)
} else {
log.Println("Success!")
}
}
The following are the correct connection strings, but they differ depending on which version of App Engine you are connecting from.
App Engine Standard:
user:password#cloudsql(INSTANCE_CONNECTION_NAME)/dbname
App Engine Flexible:
user:password#unix(/cloudsql/INSTANCE_CONNECTION_NAME)/dbname
If you are migrating to the second generation Go App Engine (Golang 1.11) change your connection string from:
user:password#cloudsql(instanceID)/db
to
user:password#unix(/cloudsql/instanceID)/db
https://cloud.google.com/appengine/docs/flexible/go/using-cloud-sql
For new people to GO, App Engine and CloudSQL just writing the simplest GO program to connect and communicate with your CloudSQL 2nd Gen database is frustrating!
You have choices to make, App Eng or App Eng Flex, SQL 1st or 2nd Gen.... Depending on the combination connection strings are different. All of google's documentation when you search drives you to first gen SQL and App Engine without flex because this is what is predominantly in production. Make sure you are reading Flex documentation if you are doing that. Make sure you are reading 2nd Gen docs if doing that. Sometimes they are entirely different docs, sometimes the documentation is stacked on a page and you have to goto the bottom to see about the newer stuff 2nd gen sql and app eng flex.
CloudShell is tricky, I still cannot compile GO and talk to SQL 2nd here. I am successfully talking to cloud sql 2nd gen from a deployed app engine flex WITH A SQL PROXY RUNNING, you have to use SQL PROXY. You have to go thru the setup for this create users on appengine and SQL.
This is my working program.
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"log"
"fmt"
"net/http"
)
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
}
func main() {
http.HandleFunc("/", handle)
http.HandleFunc("/_cloudshellProxy/_ah/health", healthCheckHandler)
log.Print("Listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handle(w http.ResponseWriter, r *http.Request) {
const dbIP = "104.xxx.xxx.x"
const dbInstanceName = "projectname:us-central1:sqlinstance"
const dbName = "servxxx"
const dbUserName = "sqlproxysuser"
const dbPassword = "xxxRockxxx"
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
fmt.Fprint(w, "Hello SQL! Hello?")
fmt.Fprint(w, "\n")
const dbOpenString = dbUserName + ":" + dbPassword + "#unix(/cloudsql/" + dbInstanceName + ")/" + dbName
//const dbOpenString = dbUserName + ":" + dbPassword + "#cloudsql(" + dbInstanceName + ")/" + dbName
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=- SQL OPEN Statement, per docs, DOES NOT return an error ever
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
db, err := sql.Open("mysql", dbOpenString);
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Fprint(w, "Failed Connection" + " " + dbOpenString)
fmt.Fprint(w, "\n")
fmt.Fprint(w, err)
return
} else {
fmt.Fprint(w, "SUCCESSFUL CONNECTION" + " " + dbOpenString)
fmt.Fprint(w, "\n")
}
_, err = db.Exec("CREATE TABLE IF NOT EXISTS exercisecloudsql101 (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, description TEXT, PRIMARY KEY (id))")
if err != nil {
fmt.Fprint(w, "CREATE TABLE failed:")
fmt.Fprint(w, "\n")
fmt.Fprint(w, err)
fmt.Fprint(w, "\n")
} else {
fmt.Fprint(w, "SUCCESSFUL CreateTable" + " " + dbOpenString)
fmt.Fprint(w, "\n")
}
}
Have run in to the same problem of connecting to a cloud SQL instance. One variant that I got working on my windows localhost environment is below. The IP of my localhost needs to be added to Authorized networks for the db instance.
Windows localhost connect over tcp:
user:password#tcp(104.xxx.xxx.xxx:3306)/dbname

Resources