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.
Related
I am trying to connect to the MySQL database using this code client_v is the name of the table I want to get data from.
I went through a lot of similar questions here but I really haven't found an answer to this question.
using MySql.Data.MySqlClient;
private void Form1_Load(object sender, EventArgs e) {
try {
string connetionstring = "Server=a029um.forpsi.com;Uid=userlogin;Pwd=userpassword";
string mysql = "SELECT * FROM dbname.cilent_v";
MySqlConnection conn = new MySqlConnection(connetionstring);
MySqlCommand command = new MySqlCommand(mysql, conn);
conn.Open();
MySqlDataAdapter dtb = new MySqlDataAdapter();
dtb.SelectCommand = command;
DataTable dtable = new DataTable();
dtb.Fill(dtable);
dataGridView1.DataSource = dtb;
} catch(Exception ex) {
MessageBox.Show(ex.Message);
}
}
The error it is returning:
Unable to connect to any of the specified MySQL hosts.
Initially, I can see that you miss the Database part in your connection string.
Be sure that your connection string is valid (including valid user name and password)
For MySql, you can find here all example list
https://www.connectionstrings.com/mysql/
I also noticed that your server is hosted on the cloud (most likely shared hosting) so you need to contact the service provider and ask them to add your computer's public IP to their firewall to accept your connection.
The better practice, for the development environment, install the MySql engine and WorkBench on your local PC, and finally when you reach the point to deploy, that time change the connection string to connect to the cloud-hosted Database.
To install MySql Engine see
https://dev.mysql.com/doc/mysql-installation-excerpt/5.7/en
To install WorkBench (The database management studio) see https://dev.mysql.com/doc/workbench/en/wb-installing-windows.html
How to use WorkBench, just google some training videos on the internet.
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
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 :)
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.
I request you to read my question carefully.
You might know when you install VS2005/2008 with SQL Server Express edition, the SQL Server operates in Windows authentication mode by default. You can use the SQL Server Management Studio to change the mode to Mixed mode (Windows and SQL Server Authentication mode).
Similarly to allow the SQL Server remote connection through TCP/IP, you need to use SQL Server Configuration Manager then select Protocol for SQLEXPRESS and then change the setting for Tcp/IP option.
What i need is to automate this process programmatically using C#. That is, i need to write a c# program to change the mode or change the tcp/ip settings etc.
Can anyone provide me help on this, how could i do that?
Thank you for sharing your valuable time.
You should use SQL Server Management Objects (SMO) - this is an API for managing SQL Server programmatically.
UPDATE:
Proves to be a bit tricky: Server.LoginMode (read/write), Server.TcpEnabled and Server.NamedPipesEnabled (get only, unfortunately). In order to modify protocols, you need to examine Microsoft.SqlServer.Management.Smo.Wmi namespace (hence going from 'the other end'):
ServerProtocol - represents server protocol
ServerProtocolCollection - a collection of all protocols defined on a given server
This function in C# will enable TCP/IP Protocol and set the Login mode to Mixed mode.
See complementary information here.
here is the code:
private static bool SetServerProperties()
{
#region standardize Connection String
string tempCatalog = "master";
string temp = #"Data Source=" + dataSource + ";Initial Catalog=" + tempCatalog + ";Integrated Security=True;MultipleActiveResultSets=True";
#endregion
SqlConnection sqlconnection = new SqlConnection(temp);
SqlCommand cmd = new SqlCommand("select ##ServerName", sqlconnection);
sqlconnection.Open();
string serverName = "";
try
{
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
serverName = dr[0].ToString();
}
catch
{
MessageBox.Show("Failed to Set SQL Server Properties for remote connections.");
}
Server srv = new Server(serverName);
srv.ConnectionContext.Connect();
srv.Settings.LoginMode = ServerLoginMode.Mixed;
ManagedComputer mc = new ManagedComputer();
try
{
Service Mysvc = mc.Services["MSSQL$" + serverName.Split('\\')[1]];
if (Mysvc.ServiceState == ServiceState.Running)
{
Mysvc.Stop();
Mysvc.Alter();
while (!(string.Format("{0}", Mysvc.ServiceState) == "Stopped"))
{
Mysvc.Refresh();
}
}
ServerProtocol srvprcl = mc.ServerInstances[0].ServerProtocols[2];
srvprcl.IsEnabled = true;
srvprcl.Alter();
Mysvc.Start();
Mysvc.Alter();
while (!(string.Format("{0}", Mysvc.ServiceState) == "Running"))
{
Mysvc.Refresh();
}
return true;
}
catch
{
MessageBox.Show("TCP/IP connectin could not be enabled.");
return false;
}
}
What about modifying the registry?
Client Protocol Settings are stored here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\SNI9.0
Check out ProtocolOrder.
Authentication Mode is stored here:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.1\MSSQLServer\LoginMode
See:
Authentication Settings
I was able to do this with a small footprint by executing this stored procedure from C#:
USE [master]
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', REG_DWORD, 2
GO
It doesn't look like much but works flawlessly and instantly, without restarting services.
I think you could solve your problem making a silent installation of SQL Server Express edition using a configuration file for the install process.
In this link you can find the command line parameters for the installation.
In this one you can find how to make your configuration file.