How do I connect to Google Cloud SQL Server using C#? - c#

I just set up a SQL Server on the "Google Cloud Platform." I created a database and tables there. I used Microsoft's "SQL Server Management Studio" (SSMS) to connect and create the database and tables. That all worked. I set up a proxy address 127.0.0.1:1443 according to Google's Cloud SQL instructions. That all worked.
However, what I want to do is connect to this remote server using a C# application. I have no problem using the C# program to connect to the SQL Server on my machine, but I can't figure out how to configure to connect to the one on the remote one on the Google Cloud Platform.
For my code I'm using the System.Data.SqlClient library.
My connection string is below. The code below is hopefully enough to tell you what is going on. When I call loadInfoFromDatabase(), it fails when it hits `connection.Open(). I wrote "FAILS HERE" next to it in the code below.
The connection string is a bit of a guess after trying different things. Any help would be appreciated.
Thanks!
public string _connectionString = #"Server=127.0.0.1:1443;Database=MarsDatabase;User Id=sqlserver;Password=AAABBBCCC";
private void loadInfoFromDatabase()
{
string firstName, middleName, lastName, email, password, assignedTables;
string connectionString;
SqlDataReader dataReader;
connectionString = _connectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); //FAILS HERE...
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("loadInfoFromDatabse");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = "Select * From Info";
// Attempt to commit the transaction.
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
...
}
dataReader.Close();
command.Dispose();
// connection.Close();
transaction.Commit();
Console.WriteLine("Selection from managers table worked.");
}
catch (Exception ex)
{
}
}
}

I see that you're using Cloud SQL Proxy to connect to the SQL Server instance using TCP.
The problem is with your connection string because you're missing the TCP prefix. By looking at Server on ConnectionString property you can see the description where:
The TCP format must start with the prefix "tcp:". (ex. server=tcp:servername, portnumber)
To fix the issue, change your connection string to:
#"Server=tcp:127.0.0.1,1443;Database=MarsDatabase;User ID=sqlserver;Password=AAABBBCCC";

Related

Connect and insert data from my computer to server's MySQL DB table with the help of C#.NET

I want to connect with a server's MySql DB(cpanel) . Though there are no errors every time I'm getting a message for Messegebox : unable to connect to any of the specified any of the MySql hosts.
using MySql.Data.MySqlClient;
connString = "SERVER = ********;PORT=3306;DATABASE=********;UID=**********;PASSWORD=*********";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Server is online");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{ MessageBox.Show(ex.Message);}
If you try to connect to your MySQL server externally, external connections need to be enabled.
Be aware that it is a security hole if you provide your app to others which contain the DB information. To go around that, you need to create a Web-API.
The first step to connect to your app to a remote server MySql Server is verify if it allows external connections, for default the root user is locked, to allow local you can try to connect with the root user typing the following command in MySql:
GRANT ALL PRIVILEGES ON *.* TO 'root'#'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
'root': You can change it with your user.
'%': allows all connections, you can limit it typing an IP.
Second step is verify your MySql .net connector
Cheers!
I would look into using ConnectionStringBuilder. Also note the use of 'using'. This will ensure resources are disposed once finished with.
private MySqlConnectionStringBuilder sConnString = new MySqlConnectionStringBuilder
{
Server = "",
UserID = "",
Password = "",
Database = ""
};
private void Test(){
// open connection to db
using (MySqlConnection conn = new MySqlConnection(sConnString.ToString()))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
try
{
conn.Open();
cmd.CommandText = "SELECT * FROM foo WHERE OrderID = #OrderID";
// Add any params
cmd.Parameters.AddWithValue("#OrderID", "1111");
cmd.Prepare();
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
return;
}
}
}
}

Find Informix Db Locale

I am having below piece of code where i try to connect to IBM's Informix database.
public void MakeConnection()
{
string ConnectionString =
#"Database=databasename;
Host=ipaddress;
Server=servername;
Service=port;
Protocol = olsoctcp;
UID = userid;
Password = password;";
IfxConnection conn = new IfxConnection();
conn.ConnectionString = ConnectionString;
try
{
conn.Open();
}
catch (IfxException ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
Getting below error on opening a connection.
ERROR [HY000] [Informix .NET provider][Informix]Database locale information mismatch.
When i try connecting using windows ODBC Data sources application, by creating a new user data source under User DSN and providing all necessary values under each section of Informix ODBC driver setup, i am able to connect successfully.
All i understand is that the client application's and database's Database Locale value should be same for proper query execution, and i have tried using en_US.57372 and en_US.UTF8 DB Locale while configuring in user DSN's which worked pretty well. I am posting here a image for better understanding.
Appreciate if anyone can help me in knowing where i can find DB Locale configured for in an Informix database and also in detail on what actually causes for this error.
Finally able to connect to database from test application!. Okay here we go,
Step 1: First we need to find what Database locale that database allows us to use? so following #Luis Marques way as he mentioned in comment section, found that Database Locale used is en_US.57372, also en_US.UTF8 is supported.
Step 2: By default, connection object's client locale and database locale property values will be whatever default value was set when Informix ODBC driver was installed.
Slightly modified my test app code as below,
public void MakeConnection()
{
string ConnectionString = "Database=databasename;Host=ipaddress;Server=servername;Service=port;Protocol = olsoctcp; UID = userid; Password = password;";
IfxConnection conn = new IfxConnection();
conn.ConnectionString = ConnectionString;
conn.ClientLocale = "en_US.UTF8";
conn.DatabaseLocale = "en_US.UTF8";
try
{
conn.Open();
}
catch (IfxException ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
So manually assigning client and database locale values for connection object with what we have got in step 1 solved the issue.

C# Connection mysql with self signed

Is self signed certificate disrupting connection to mysql?
I already give action crud in data and grant access to administration.
but the connection still got error.
Unable to connect to any of the specified MySQL hosts
my team connection like this:
Catalog=devbaf;User Id=userclient;password=client123
connection code:
try
{
string constring = "SERVER=123.45.678.9;DATABASE=devbaf;User Id=backendsystem;PASSWORD=1q2w3e4r5t;";
using (MySqlConnection con = new MySqlConnection(constring))
{
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM users"))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
gvtest.DataSource = dt;
gvtest.DataBind();
}
}
}
}
}
catch (Exception e)
{
Response.Write(e.Message.ToString());
}
explanation problem:
I make a database in local server, so my friend can access to it to insert data. but when he make a connection script it wont connect to my database but can connect to server. He already tries to move some file to the server and it works,but the connection to database wont connect. i don't have an experience for this coz im php programmer not c# programmer. hope my explanation is clear.
I have found your error message like trying to connect the host but in your connection string is missing the MySQL server name or host address. I hope if you add the MySQL hostname or server address to your connection. it will fix your issue.
you can try this
string connectionString ="SERVER=servername; DATABASE=databasename; User Id=userid; PASSWORD=password;";

Connection to SQL Server throws exception

I have a task where I need to write a simple application to process some data from SQL Server. The process is working with dummy data, but I just can't connect to the server to get the valid data.
I have a code like this:
string ConnectionString = #"Server=----;Database=----;User ID=----;Password=*******";
string field1, field2;
try
{
using (SqlConnection Connection = new SqlConnection(ConnectionString))
{
Connection.Open();
using (IDbCommand dbcmd = Connection.CreateCommand())
{
string sql = "SELECT * from [---].[dbo].[Components]";
dbcmd.CommandText = sql;
using (IDataReader reader = dbcmd.ExecuteReader())
{
while (reader.Read())
{
field1 = (string)reader["field1"];
field2 = (string)reader["field2"];
}
}
}
}
Console.WriteLine("Success");
}
catch (Exception e)
{
Console.WriteLine("Failure");
Console.WriteLine(e.Message);
}
My problem is, that if I run this code in a simple C# application, it works, no problem, but when I try to use it in the Xamarin application, the Connection.Open() throws an exception with the message:
server does not exist or connection refused
And here it is my problem, I don't really know why this happenes, when I run it as an app. The problem shows up even in android emulator, which theoretically uses the same network as the c# application which works.
Do I need to change options in the app, or the problems is at the server side?
I know that it's not the best idea to connect directly, but the app will be used internally on a secured network, so that this shouldn't be the problem.
Android emulator does not set correct DNS network parameters, so your application is not able to resolve the domain name of your SQL server.
So in your connection string try setting the IP address of SQL server instead of domain name.
string ConnectionString = #"Server=192.168.XXX.XXX;Database=MyDatabase;User ID=MyUser;Password=MyPassword";

connect to MySQL webserver with C#

I try to connect to a MySQL database on a server a friend of mine has created, but it still says it cannot connect to the server!
Here is my code:
String connectionString = "Persist Security Info=False;database=qwertyui;server=www.qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO etc.... ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue( etc.... );
connection.Open();
int r = cmd.ExecuteNonQuery();
}
It failes on the connection.Open() instruction throwing an exception -> cannot connect to the server.
Any ideas please?
SqlConnection is a SQL Server client.
You need to download a MySql client from NuGet.
First download the MySQL Connector.
Make sure you add a reference to the DLL (+ set copy local to true !)
Add using MySql.Data.MySqlClient; on top of your class.
As for the Connection String, do not add http or www in front of server. As it will try to connect to apache (port 80) instead to MySQL. The default port of MySQL is 3306.
string connectionString = "Persist Security Info=False;database=qwertyui;server=qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;port=3306";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
string query = "INSERT INTO table VALUES (#parameter)";
connection.Open();
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#parameter", parameter);
cmd.ExecuteNonQuery();
}
}
If this is not working. Make sure MySQL allows remote access, if this is not the case, you can keep trying forever without any result.
First thing that comes to mind is that you will have to use a MysqlConnection and command.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html
Is it a local database?
And if with all of above does not work try to get grant to all privileges(GRANT Syntax)!
Basically it will go something like:
GRANT ALL PRIVILEGES ON DBname.* to 'username'#'IPadress' IDENTIFIED BY 'password';

Categories

Resources