Unknown MYSQL server host 'ServerName'(11001) - mysql

I want to try connection with MySQLdatabase with my Delphi Application.
I am using dbXpress component TSQLConnection.
When I tried using the Graphic component and test it if it can connect Database.
It got connected with using Object inspector option.
But when I tried using the code I am getting error as Unknown MYSQL server host 'ServerName'(11001).
I am not able to get the right solution from google uncle.
Can anyone tell me whats wrong with my code?
Below is My Code.
Conn := TSQLConnection.Create(nil);
try
conn.DriverName:= 'MySQL';
conn.Params.Add('HostName=127.0.0.1');
conn.Params.Add('Database=test1');
conn.Params.Add('UserName=root');
conn.Params.Add('Password=test');
conn.LoginPrompt := false;
try
conn.Connected := true;
ShowMessage('Database connected');
Except
on E:exception do
ShowMessage(E.Message);
end;
finally
if Conn.Connected then
Conn.Connected := false;
FreeAndNil(Conn);
end;
Please let me know if any more information needed.
Thanks in advance.

The conn.Params list is already propagated with pre-existing values. Therefore you should not .add() your configuration to it, but rather change the current Params.
So, instead of using
conn.Params.Add('HostName=127.0.0.1'); // wrong - should update, not add
conn.Params.Add('Database=test1'); // wrong - should update, not add
conn.Params.Add('UserName=root'); // wrong - should update, not add
conn.Params.Add('Password=test'); // wrong - should update, not add
Use
conn.Params.Values['HostName'] := '127.0.0.1';
conn.Params.Values['Database'] := 'test1';
conn.Params.Values['UserName'] := 'root';
conn.Params.Values['Password'] := 'test';

Related

How to switch between databases using GORM in golang?

I'm new to GORM in golang. I'm stuck at a point. Generally we select the database like this:
DBGorm, err = gorm.Open("mysql", user:password#tcp(host:port)/db_name)
But my problem is I'll get the 'db_name' in the request, which means I don't know which db_name might come and I'll have to query according to that db_name.
So now, I'll create the database pointer in the init function like this:
DBGorm, err = gorm.Open("mysql", user:password#tcp(host:port)/) which is without the db_name.
Now how will I switch to db_name coming to me in request. Because when I try to do DBGorm.Create(&con), it shows No database selected.
If I use 'database/sql', then I can make raw queries like this: "SELECT * FROM db_name.table_name", this can solve my problem. But how to do this in gorm?
You can explicitly specify db_name and table_name using .Table() when doing query or other operation on table.
DBGorm.Table("db_name.table_name").Create(&con)
I saw a related article on Github. https://github.com/go-sql-driver/mysql/issues/173#issuecomment-427721651
All you need to do is
start a transaction,
set you database
run your desired query.
and switch back to your desired DB
commit once you are done.
below is an example
tx := db.Begin() // start transaction
tx.Exec("use " + userDB) // switch to tenant db
tx.Exec("insert into ....") // do some work
tx.Exec("use `no-op-db`") // switch away from tenant db (there is no unuse, so I just use a dummy)
tx.Commit() // end transaction

Is there a right way to connect to MySQL?

I've come across documentation that says:
the sql.DB object is designed to be long-lived. Don’t Open() and
Close() databases frequently. Instead, create one sql.DB object for
each distinct datastore you need to access
source
And doing some poking around I mostly found code opening the connection in the handler file as so
func dbConn() (db *sql.DB) {
dbDriver := "mysql"
dbUser := "root"
dbPass := "root"
dbName := "goblog"
db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"#/"+dbName)
if err != nil {
panic(err.Error())
}
return db
}
source
And to access the db
db := dbConn()
This is called in the functions that need to use it, to my understanding this would open the connection and then close it when it reaches the end of said function.
Wouldn't this be violating the quote above?
The example is simply poorly written, and Yes you shouldn't Open and Close unless its different datastores.
Open returns DB and
DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines

Config for GoLang Returns "non-name" error

I am having trouble compiling code Google-Cloud offers on connecting to a mysql database remotely using Golang.
The code is a direct copy-paste from here: https://cloud.google.com/sql/docs/mysql/connect-external-app#go. One may also look here: https://github.com/GoogleCloudPlatform/cloudsql-proxy/blob/master/proxy/dialers/mysql/hook_test.go.
I've tried providing a second variable to the first line below, but there is an error as only one value is returned by the mysql function.
The troublesome code is on the second line, possibly due to the first line.
cfg := mysql.Cfg("haveibeenexploited:us-west1:hibe", "username", "password")
cfg.DBName := "mythril"
db, err := mysql.DialCfg(cfg)
searchcontract/searchcontract.go:67:5: non-name cfg.DBName on left side of := is the error message I get.
Change this line of code:
cfg.DBName := "mythril"
to:
cfg.DBName = "mythril"
The := operator declares a new variable and assigns it a value. This is called "Short Variable Declarations". Since DBName is part of the structure cfg you are using the wrong operator. The correct operator to use is the assignment operator =.

Autohotkey close database connection

I have made a script using the following library;
http://www.autohotkey.com/board/topic/72629-mysql-library-functions/
to connect to my non-local database. However I'm issuing some max_user_connections problems and I think this is due to the fact that I never close the database connection.
I can't seem to find a way to do that using this library but I am not certain, maybe theres a way to close any connection to the internet or any database or whatever that would work build-in in AHK?
Script:
hi() {
mysql := new mysql
db := mysql.connect("x","x","x","x") ; host,user,password,database
if db =
return
sql =
(
UPDATE something
SET yo = yo+1
WHERE id = 1
)
result := mysql.query(db, sql)
}
Thanks in advance
The DLL of the AHK script has the mysql_close function, but it's not coded into the AHK library.
You can technically manually call the DLL just like the AHK and see if it'll work.
Since I also need to connect to a MySQL DB via AHK, I'll update this answer when a full solution is available.

Entity Framework : Set MySQL custom environment variables

I have an issue with Entity Framework 5.0. I'm working with Silverlight 5 and MySQL 5.6 too.
I need to set an environment MySQL variable before each connexion to the MySQL server.
E.g
SET #my_var = 'test';
Under Mysql I don't have any issues.
The following raises an EntityFrameworkException (syntax error near '#').
this.ObjectContext.CreateQuery<object>(" SET #my_var = 'test' ");
OR
this.ObjectContext.CreateQuery<object>(" CALL set_my_var('test') ");
This last method raises a MySQLException saying that a DataReader is already open and need to be closed.
this.ObjectContext.ExecuteStoreQuery<object>(" CALL set_my_var('test') ", null);
I also tried to set a MySQL system environment (no '#') with the same result every time.
Any help will be much appreciated !
Thank you.
I tried so many things that I misspelled my variable in my code.
So the following finaly worked : ctx.ExecuteStoreCommand("SET #my_var = 'test'");
I decided to leave the instruction in the method Initialize of my domain service. This method is inherited of the LinqToEntitiesDomainService class.
But you need to set Allow User Variables=True in your MySQL connection string
(ref : Is it possible to use a MySql User Defined Variable in a .NET MySqlCommand?)
You simply need to use a recent version of the MySQL Connector because older versions use the '#' mark to define SQL parameters so it could conflict with custom variables. Now it uses the '?' mark : http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlcommand.html
My library was already up to date (6.6.5).
Thank you for the help !
Since your statement is not a query (i.e. does not return any result) you should use ExecuteStoreCommand. Something like this should work:
ctx.ExecuteStoreCommand("SET #my_var = 'test'")