Connection String Problem Oracle .Net - c#

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.

Related

Accessing legacy Visual FoxPro database from C#

I have a legacy Visual FoxPro database from which I need to get the data from.
I have DBC, DCT, DCX & FPT files in the database folder.
I installed the Visual FoxPro provider & driver and wrote a short C# program to access the data.
I also made sure the program is running in 32bit mode, since I understood that the VFP driver is 32bit.
However I'm getting the following error:
Additional information: Connectivity error: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I made sure that the driver name ("Microsoft Visual FoxPro Driver") as appears in the Windows ODBC 32bit administration tool is specified in the connection string, but it doesn't seem to help.
The code:
OleDbConnection yourConnectionHandler = new OleDbConnection(
#"Provider=VFPOLEDB.1;DRIVER=Microsoft Visual FoxPro Driver;Data Source=mydatabase.dbc;Mode=Read;Collating Sequence=machine");
// Open the connection, and if open successfully, you can try to query it
yourConnectionHandler.Open();
if (yourConnectionHandler.State == ConnectionState.Open)
{
string mySQL = "select * from tablename";
var command = yourConnectionHandler.CreateCommand();
command.CommandText = mySQL;
var res = command.ExecuteReader(); // throws the error
yourConnectionHandler.Close();
}
I've been stuck on this for a long time, and have tried everything I could find on the net.
Any idea?
You are saying provider and trying to use OleDbConnection (which is right) but defining an ODBC driver within the connection string. In other words, your connection string is wrong.
using (OleDbConnection cn = new OleDbConnection(
#"Provider=VFPOLEDB;Data Source=c:\MyPath\mydatabase.dbc;Mode=Read;Collating Sequence=machine"))
using (OleDbCommand cmd = new OleDbCommand("select * from tablename", cn))
{
cn.Open();
var reader = cmd.ExecuteReader();
// do something with the reader. ie:
// someDataTable.Load(reader);
cn.Close();
}
It works wonderfully well. In connectionstring you don't need to use the database name, you can just use the tables' path as the data source.

How to connect to phpmyadmin mysql database using c# (using Mysql.Data.MysqlClient;)

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.

Insert integer value into SQL Server database from C#

I am trying to insert an integer value into a SQL Server database as below when I run the program there are no any errors, but the table doesn't get updated with values. I have searched on the internet and I am doing the same can anyone help to find what I am doing wrong.
Note: I already defined "connectionString" as a string on the form class
private void btnUpdate_Click(object sender, EventArgs e)
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
MessageBox.Show("Done !!");
}
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MainDataBase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MainDataBase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Code Seems correct,Perhaps you are checking the wrong DB?. I would add a Try/catch for exceptions. And remember to close connection after executing query. Regards
check your database column datatype,use try catch.
and try to replace cmd.Parameters.AddWithValue("#TotalIncome", totalincome); to cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
try
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(#"INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totaldeductions;
//cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
//cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}

Application keep old sql connection when switch database (C#)

I have two SQL Server databases, server name are sql1 and sql2.
When I switch database from sql1 to sql2 (using HaProxy), my application still keeps the old SQL connection to server sql1.
However, other applications (using Linq-to-SQL) can get the new SQL connection to sql2.
Please see my code below that's I using to get connection to SQL Server:
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
conn.Open();
//do something...
conn.Close();
return data;
}
}
What's my problem? How can I resolve this? Thanks!
You need to know the HAProxy listen configuration, maybe your HAProxy has exceptions programmed, or the redirection only works if you use an specific IP address destination or come from an specific IP range. Please compare the connections string used in each case.
https://www.stevefenton.co.uk/2016/11/load-balancing-microsoft-sql-server-with-haproxy/

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.

Categories