c# connect into MySQL - c#

I'm trying to connect MySQL in C# develope in Expression Blend 4
but i get following error ?
try
{
string serverConnection = "SERVER=xxx.xxx.xxx.xxx; UID=xxx; PASSWORD=xxx; DATABASE=xxx;";
MySqlConnection conn = new MySqlConnection(serverConnection);
conn.Open();
MessageBox.Show("Successfully connected");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error:"+ex.Message);
}
Here is the error:
Unable to connect to any of the specified MySQL hosts

The format for connection strings is as follows,
Server=myServerAddress; Port=1234; Database=myDataBase; Uid=myUsername; Pwd=myPassword;
The most likely issue is that you are trying to remotely connect to your MySQL server in which case make sure it allows for remote connections, and then you must check and make sure the user you are trying to login as is allowed to connect from either your public IP or any public IP.
NOTE: I know this response is 2 and 1/3 years late, but I wanted this to be here for anyone else with a similar issue.

I think its more of like the placement of the parameters.
The standard format specified is this:
Server=myServerAddress; Port=1234; Database=myDataBase;
Uid=myUsername; Pwd=myPassword;
You need to change it like this:
string serverConnection = "SERVER=xxx.xxx.xxx.xxx; DATABASE=xxx; UID=xxx; PASSWORD=xxx;";
Try to change and see if that works :)

Related

SQL Server 2014 Express and C# (System.Data.Sql.SqlDataSourceEnumerator.Instance.GetDataSources())

Before you say anything: I have done the searching. I have seen the countless posts on StackOverflow about connecting to a named instance of SQL Server Express via C#.
But this is just weird. Using my SQL Server browser in Visual Studio, I am able to see AND connect to the named instance of SQL Server Express. However when I try to programmatically create a connection string using the GetDataSources() method (which is working fine for me btw), I am unable to connect to the SQL Server.
I have verified the connection string output of the program with the connection string that Visual Studio uses to connect via the SQL Server Management Studio. I know I have TCP/IP and Named Pipes enabled in the manager. And my Server Browser is indeed running as well (or I wouldn't be able to see my server under GetDataSources())
So: does anybody have any ideas as to why (when the connection string is the same) my program cannot connect to my instance of SQL Server 2014 Express? But Visual Studio can. ANY help would be greatly appreciated. Cheers y'all!
EDIT I have included my code to generate a connection string:
private void ConnectToServer(object sender, RoutedEventArgs e)
{
if(serverView.SelectedIndex >= 0)
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(string.Format(
#"Server={0}/{1};", (Environment.MachineName == SQLManager.servers.Rows[serverView.SelectedIndex]["ServerName"].ToString()) ? "(local)" :
SQLManager.servers.Rows[serverView.SelectedIndex]["ServerName"].ToString(),
SQLManager.servers.Rows[serverView.SelectedIndex]["InstanceName"].ToString())
);
builder.IntegratedSecurity = true;
bool success = false;
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = builder.ConnectionString;
try
{
con.Open();
SQLManager.conString = new SqlConnectionStringBuilder(builder.ConnectionString);
CreateDatabseIfNotExist();
success = true;
}
catch (SqlException ex)
{
MessageBox.Show(builder.ConnectionString, "Connection Error", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
}
As of now the connection string output (for Visual Studio) is:
Data Source=VIRTUAL-DEV-PC\MSQLSERVER;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
My generated connection string (on the local machine where server is running):
Data Source=(local)\MSQLSERVER;Integrated Security=True
NOTE: I have also tried replacing (local) with <VIRTUAL-DEV-PC> <= machine name

How to connect to oracle database with ODAC c#

I am using this code but getting an error of 'Object reference not set to an instance of an object.' at con.open() ? what am I doing wrong ?
I have already download and installed ODAC component version 10 , 11 ,12 trying each one at the failure of the latest one but still same error
using Oracle.DataAccess.Client;
namespace WindowsFormsApplication1
{
class OraTest
{
public OracleConnection con = new OracleConnection();
public void Connect()
{
con.ConnectionString = "Data Source=(DESCRIPTION= (ADDRESS = (PROTOCOL = TCP)(HOST =myip) (PORT = myport))(CONNECT_DATA = (SERVER = dedicated)(SERVICE_NAME = mydb)));User ID=myid;Password=mypass;";
con.Open(); //error here
}
public void Close()
{
con.Close();
con.Dispose();
}
}
Please go through this link
Getting Started with Oracle Data Provider for .NET (C# Version)
http://www.oracle.com/webfolder/technetwork/tutorials/obe/db/dotnet/GettingStartedNETVersion/GettingStartedNETVersion.htm
If you add a try/catch block in Connect(), you'll be able to catch the error.
For example:
When opening an oracle connection, connection object is null
I added the try catch block, and it returned ORA12154 - TNS could not
be resolved. After some research, I added an SID to my tnsnames.ora
file in my ODP for .NET Oracle home path, and it worked
See also Troubleshooting Oracle Net Services for troubleshooting possible connection issues from Oracle clients (such as your C# program).
But your first step is absolutely to determine the Oracle-level error (for example, ORA-12543 (could not connect to server host) or TNS-12514 (could not find service name)
MSDN: OracleException Class
public void ShowOracleException()
{
OracleConnection myConnection =
new OracleConnection("Data Source=Oracle8i;Integrated Security=yes");
try
{
myConnection.Open();
}
catch (OracleException e)
{
string errorMessage = "Code: " + e.Code + "\n" +
"Message: " + e.Message;
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
log.Source = "My Application";
log.WriteEntry(errorMessage);
Console.WriteLine("An exception occurred. Please contact your system administrator.");
}
}
It's significant that con.ConnectionString = xyz works, but the following `con.Open()" fails. This means .Net is creating the C# object, but Oracle/TNS is failing when you try to use it.
ADDITIONAL SUGGESTIONS:
Re-read
When opening an oracle connection, connection object is null.
Read all of the suggestions, including the one about "Data Source in your connection string".
Focus on your connection string. It couldn't hurt to specify the connection string in your OracleConnection() constructor, if possible. Here's another link:
ODP.NET Connection exception
It would be great if you can verify connectivity from your PC with some other Oracle client, besides your C#/.Net program. To verify you're talking to the right TNS host and service, with the correct username/password. For example, maybe you have SQLDeveloper or sqlplus.
Finally, re-read the TNS troubleshooting link:
https://docs.oracle.com/cd/E11882_01/network.112/e41945/trouble.htm#NETAG016
What worked for me with the same error was to simply switch from the 'plain' Oracle DataAccess library, to the 'Managed' version.
This is an extemely easy change to make -
Add a Reference in your c# project to the Oracle.ManagedDataAccess library
Replace the existing use statements at the top of your Oracle client code with the following:
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
Include the Oracle.ManagedDataAccess.dll file with your exe

Informix db connection and loading to datatable is not working

i am trying to connect to an informix database in my web application and retrieve the data based on an item code entered by the user and store it in a datatable later i want to take the data from the datatable and display it on my textboxes for the item selected. its an odbc connection DRIVER={IBM INFORMIX ODBC DRIVER} in my connection string
if (DropDownList4.Text == "***.**.**.**" || DropDownList4.Text == "***.**.**.**" || DropDownList4.Text == "***.**.**.**")
{
//string abilene = ConfigurationManager.ConnectionStrings["Abeliene"].ConnectionString.ToString();
IfxConnection conn = new IfxConnection("User Id=****;Password=****;" +"Host=abkrisc1;Server=abkrisc1;" +"Service=1719;DB=circa119;");
DataTable Abilene = new DataTable();
Abilene.Columns.Add("item");
Abilene.Columns.Add("desc");
Abilene.Columns.Add("upc");
Abilene.Columns.Add("itemupc");
Abilene.Columns.Add("ctyp");
Abilene.Columns.Add("citg");
Abilene.Columns.Add("best");
Abilene.Columns.Add("disp");
Abilene.Columns.Add("mold");
Abilene.Columns.Add("csel");
IfxCommand cmd;
cmd = new IfxCommand("Select t_item,t_idsc,t_upct,t_item_upc,t_ctyp,t_citg,t_best,t_disp,t_mold,t_csel from tsckcm907 where t_item = #item'");
conn.Open();
cmd.Parameters.Add("#item", IfxType.VarChar).Value = TxtItem.Text;
try
{
IfxDataReader myreader = cmd.ExecuteReader();
Abilene.Load(myreader);
Response.Write(Abilene.Columns);
con = true;
}
catch (Exception ex)
{
throw ex;
con = false;
}
if (con == true)
{
while (Abilene.Rows.Count > 0)
{
TxtItem.Text = Abilene.Rows[0]["item"].ToString();
lbldesc.Text = Abilene.Rows[1]["desc"].ToString();
}
}
The error i get when i debugged was at conn.open() -> ERROR [HY000] [Informix .NET provider][Informix]Server abkrisc1 is not listed as a dbserver name in sqlhosts.
i have done a similar scenario with sql database, but informix i have never worked with. Please if anyone could help me with this code that would be awesome, even this code that i used was found from ibm website.
Check your informix server configuration (the problem might be in your sqlhosts file, as the error states), it should contain server with the name abkrisc1, listening at port 1719.
If that's ok, then check your DSN configuration (this may vary depending on your operating system - check out this page for details).
Documentation in internet and the error message are misleading.
I had the same error and meanwhile I found out how to solve it.
When you install the Informix Client SDK for Windows and use the ODBC driver for Informix (with or without .NET) you must pass the following parameters:
Host
Server
Service or Port
Protocol
User ID
Password
All these parameters are mandatory. The database is optional.
In your connection string the protocol is missing. In the case that any parameter is missing the OBDC driver searches the server in the registry under
32 bit driver:
HKLM\Software\Wow6432Node\Informix\SQLHOSTS\Servername
64 bit driver:
HKLM\Software\Informix\SQLHOSTS\Servername
If the server is not listed there you get the error "Server XYZ is not listed as a dbserver name in sqlhosts."
Please note that only Linux uses an sqlhosts file. On Windows the same data is stored in the registry instead.
You do NOT need to create a sqlhosts file although the error message and the documentation and several webpages make you think that.
You do NOT need to use the IBM tool SetNet32 to generate entries for your server.
You just have to pass ALL mandatory parameters to the ODBC driver and the error is gone.
It is really a pitty that IBM is not able to give a more intelligent error message.

Sybase ODBC Driver Client unable to establish connection

I am trying to hit a remote Sybase database using ODBC. I have written a C# program with the following code
try
{
String conString = "Driver={Adaptive Server Enterprise};server=ipAddress;port=portNumber;db=databaseName;uid=strUserName;pwd=strPassword";
con = new OdbcConnection(conString);
con.Open();
}
catch (Exception exp)
{
con = null;
}
After the connection times out ,the exception message says :-
ERROR [08001] [Sybase][ODBC Driver]Client unable to establish a connection
On Debugging the code when I hover on "con.Open()", the ServerVersion attribute of the connection object displays the following message 'con.ServerVersion' threw an exception type 'System.InvalidOperationException'
Can anybody help me in finding out the reason for this exception..?
I would double check first that you can connect via a normal SQL client (e.g. isql, Aqua etc) on the same hostname and port.
However that looks from a quick google like a possible Sybase Adaptive Anywhere (as opposed to Enterprise) error so are you using the right driver for the type of database? They are two different products.

Connection String Problem Oracle .Net

I am new to oracle and am trying to simply connect to an oracle db, but I am not sure where to find the proper credentials to put in the connection string. I simply downloaded and install oracle express edition on my machine, then installed the .Net references. My simple code is here:
string oradb = "Data Source=XE;User Id=hr;Password=hr;";
OracleConnection conn = new OracleConnection(oradb); // C#
try
{
conn.Open();
string sql = "SELECT FIRST_NAME FROM EMPLOYEES WHERE EMAIL='SKING'"; // C#
OracleCommand cmd = new OracleCommand(sql, conn);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader(); // C#
dr.Read();
//label1.Text = dr["dname"].ToString(); // C# retrieve by column name
label1.Text = dr.GetString(0).ToString(); // return a .NET data type
//label1.Text = dr.GetOracleString(0).ToString(); // return an Oracle data type
}
catch (OracleException ex)
{
label1.Text = ex.Message;
}
finally
{
conn.Close();
}
I am getting a TNS:could not resolve the connect identifier specified exception. Its probably because my connection string is wrong is what I am guessing. I cannot even go to the Server Explorer dialog in Visual Studio and test a connection correctly to my oracle db.
What steps do I need to take to figure out the proper credentials to plug into my connection string?
Or wording it like this....
If you were going to install oracle express on your machine, then connect to a .Net app what steps would you take to set up the connection string?
Maybe it is looking for a data source defined in a tnsnames.ora file called XE.
Try the Easy Connect naming method in the Express edition. It enables application clients to connect to a database without using any configuration files, simply by specifying the data source attribute through syntax shown below:
user id=hr;password=hr;data source=hr-server
user id=hr;password=hr;data source=hr-server:1521
user id=hr;password=hr;data source=hr-server:1521/XE
Replace hr-server with the dns name or ip of your machine.

Categories