Golang Unable to get instances from Sql Server Browser on host - sql-server

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.

Related

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

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

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

How to know which server is online or offline in a OAM cluster

Hello I´ve a problem when I try to monitor which one of a cluster oam servers is online and offline I use the the getServerDiagnosticInfo() method of AccessClient class from aSDK, but the Hashtable that returns only contains Keys (name and port of server) and Values that contains another HashTable (ObKeyMapVal a subtype of HashTable) but I think that this object must contains the health, server port, server name and number of connections as mentioned in the API doc but when I print the size and contents of it only prints "0" and [] (its empty)
snippet:
try{
AccessClient ac = AccessClient.createDefaultInstance("/dir",AccessClient.CompatibilityMode.OAM_10G);
Hashtable info = ac.getServerDiagnosticInfo();
Set<?> servers = info.keySet();
Collection<?> serverInfo = info.values();
System.out.println("Num of servers: " + servers.size());
Iterator it = servers.iterator();
Object servidor = null;
Object dato = null;
while(it.hasNext()){
servidor = it.next();
System.out.println("Server: " + servidor);
dato = info.get(servidor);
System.out.println("Data: " + dato);
ObKeyValMap ob = (ObKeyValMap) dato;
System.out.println("Size: " + ob.keySet().size());
System.out.println("Is Empty: " + ob.keySet().isEmpty());
System.out.println("Properties: " + ob.keySet());
}
ac.shutdown();
} catch (oracle.security.am.asdk.AccessException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
And got the next output:
Num of servers: 2
Server: myserver1.com5575
Data: {}
Size: 0
Is Empty: true
Properties: []
Server: myserver2.com5575
Data: {}
Size: 0
Is Empty: true
Properties: []
Thanks for your help !!!
Once you get the OAM Server Host and Port using getServerDiagnosticInfo(). Try to do telnet ( I am not Java Expert, following link may help How to connect/telnet to SPOP3 server using java (Sockets)?) , if the server is up the telnet session will be established.

Data encryption issues with Oracle Advanced Security

I have used Oracle Advanced Security to encrypt data during data transfer. I have successfully configured ssl with below parameters and I have restarted the instance. I am retrieving data from a Java class given below. But I could read the data without decrypting, the data is not getting encrypted.
Environment:
Oragle 11g database
SQLNET.AUTHENTICATION_SERVICES= (BEQ, TCPS, NTS)
SSL_VERSION = 0
NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)
SSL_CLIENT_AUTHENTICATION = FALSE
WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
(DIRECTORY = C:\Users\kcr\Oracle\WALLETS)
)
)
SSL_CIPHER_SUITES= (SSL_RSA_EXPORT_WITH_RC4_40_MD5)
Java class:
try{
Properties properties = Utils.readProperties("weka/experiment/DatabaseUtils.props");
// Security.addProvider(new oracle.security.pki.OraclePKIProvider()); //Security syntax
String url = "jdbc:oracle:thin:#(DESCRIPTION =\n" +
" (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))\n" +
" (CONNECT_DATA =\n" +
" (SERVER = DEDICATED)\n" +
" (SERVICE_NAME = sal)\n" +
" )\n" +
" )";
java.util.Properties props = new java.util.Properties();
props.setProperty("user", "system");
props.setProperty("password", "weblogic");
// props.setProperty("javax.net.ssl.trustStore","C:\\Users\\kcr\\Oracle\\WALLETS\\ewallet.p12");
// props.setProperty("oracle.net.ssl_cipher_suites","SSL_RSA_EXPORT_WITH_RC4_40_MD5");
// props.setProperty("javax.net.ssl.trustStoreType","PKCS12");
//props.setProperty("javax.net.ssl.trustStorePassword","welcome2");
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(url, props);
/*8 OracleDataSource ods = new OracleDataSource();
ods.setUser("system");
ods.setPassword("weblogic");
ods.setURL(url);
Connection conn = ods.getConnection();*/
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery("select * from iris");
///////////////////////////
while(rset.next()) {
for (int i=1; i<=5; i++) {
System.out.print(rset.getString(i));
}
}
Are you expecting that your SELECT statement would return encrypted data and that your System.out.print calls would result in encrypted output going to the screen? If so, that's not the way advanced security works-- Advanced Security allows you to encrypt data over the wire but the data is unencrypted in the SQLNet stack. Your SELECT statement, therefore, would always see the data in an unencrypted state. You would need to do a SQLNet trace or use some sort of packet sniffer to see the encrypted data flowing over the wire.
You'll find the documentation in "SSL With Oracle JDBC Thin Driver".
In particular you should probably use PROTOCOL = TCPS instead of PROTOCOL = TCP. I'd also suggest using a stronger cipher suite (and avoid the anonymous ones, since with them you don't verify the identity of the remote server).

Resources