Fetching data from oracle DB - c#

I use the below code to connect to my oracle DB and execute a query. The query I used in the example simply fetches a set of rows from a table. However, I keep getting an error message that "The table or view does not exist". But, I am pretty sure that the table exists in the DB. Where am I going wrong?
public void UpdateDatabase()
{
System.Data.OracleClient.OracleConnection conn = new System.Data.OracleClient.OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.144)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)));UID=mwm;PWD=mwm";
conn.Open();
OracleCommand command = conn.CreateCommand();
command.CommandText = "Select * from Task";
command.ExecuteNonQuery();
command.Dispose();
}
The error is triggered when command.ExecuteNonQuery() is reached.

I think the problem is with command.ExecuteNonQuery();
Actually you are executing a query here therefore you should use either DataAdapter or DataReader.
public void UpdateDatabase()
{
System.Data.OracleClient.OracleConnection conn = new System.Data.OracleClient.OracleConnection();
conn.ConnectionString = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.5.144)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = orcl)));UID=mwm;PWD=mwm";
conn.Open();
OracleCommand command = conn.CreateCommand();
SqlDataAdapter a = new SqlDataAdapter("Select * from \"Task\"", command))
DataTable t = new DataTable();
a.Fill(t);
command.Dispose();
}

Task is oracle Reserve Word, that is why you are getting this error. Use double quotes.
command.CommandText = "Select * from \"Task\"";
ExectueNonQuery, may not give you any error, but it will not give you the desired result. You need to do command.ExecuteReader. See the link.
You may also see this Getting Started with Oracle Data Provider for .NET (C# Version)

Related

C# SQL Connection not found

How can I connect a SQL database in C#?
My code:
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
var conn = new SqlConnection(connectionString);
conn.Open();
conn.Close();
I get: Error: 40 - could not open a connection to sql server. I tried also in Python and it worked well:
cnx = mysql.connector.connect(user='root', password='MyPassword', host='127.0.0.1', database='MyDatabase')
cursor = cnx.cursor()
What am I missing in C#?
Please use MySqlConnection for MySql DB.
const string connectionString = "Data Source=127.0.0.1;User ID=root;Database=MyDatabase;Password=MyPassword";
MySqlConnection conn = new MySqlConnection(connectionString );
conn.Open();
string sqlcommand = "SELECT Query";
MySqlCommand cmd = new MySqlCommand(sqlcommand , conn);
please follow this example
using MySql.Data.MySqlClient;
var connectionString = "server=serveradress;database=dbName;user id=sqluser;password=abc;";
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using var command = new MySqlCommand("SELECT COUNT(*) FROM tableName ", connection);
var Count = command.ExecuteScalar();
Console.WriteLine($"There are {Count } movies");
}
server adress in general is 127.0.0.1 ,if you are working locally
here the source page :
example
and also consider reading this page here docs

C# write select from mysql to variable

I have a big problem with save variable from select in mysql.
I wrote the following code:
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string query_date = "SELECT computer_name from wp_users where user_login = #login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
reader = command2.ExecuteReader();
while (reader.Read())
{
string ColumnName = (string)reader["computer_name"];
}
cnn.Close();
I tried a lot of commands like ExecuteReader , ExecuteNonQuery , ExecuteScalar. but none of them worked and I am getting the same error:
Really don't know what is wrong here I searched a lot and didn't find a solution of any form. Please help.
EDIT 1
I just did how you wrote and i did this :
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string query_date = "SELECT computer_name from wp_users where user_login = #login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
DataTable table = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command2);
adapter.Fill(table);
// This is the important line
string result = table.Rows[0].ToString();
cnn.Close();
Its the same error as earlier but another place. What's going on here... just don't know.
Additional information mean in english : The key is not present in the dictionary
EDIT 2
The funniest is when i just try to update with code :
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
MySqlDataReader reader = null;
string upd = "UPDATE w_users Set computer_name = CURRENT_DATE where user_login = #login";
MySqlCommand command2 = new MySqlCommand(upd, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
DataTable table = new DataTable("ResultTable");
SqlDataAdapter adapter = new MySqlDataAdapter(command2);
adapter.Fill(table);
cnn.Close();
And this works fine without any errors just update my table... What's the point of it
EDIT 3
I jutr try used to ExecuteScalar() and still i have the same error :
The solution is simple:
Updating mysql.data.dll to the newest version fixed it (https://dev.mysql.com/downloads/connector/net/6.9.html).
This exception wants to tell you, that there is no matching key in your resultset. Keys are case sensitive. Have you tried to spell your column name with all uppercase letters: (string)reader["COMPUTER_NAME"]?
Databases tend to return the column names in uppercase, even though you selected the column name in lower case.
If you have the MySqlDataAdapter, try if the following code works for you:
string connectionstring = #"****;userid=*****;
password=***;database=***";
cnn = new MySqlConnection(connectionstring);
cnn.Open();
string query_date = "SELECT computer_name AS `computer_name` FROM wp_users WHERE user_login = #login";
MySqlCommand command2 = new MySqlCommand(query_date, cnn);
command2.Parameters.AddWithValue("#login", metroTextBox.Text);
DataTable table = new DataTable("ResultTable");
MySqlDataAdapter adapter = new MySqlDataAdapter(command2);
adapter.Fill(table);
// This is the important line
string result = table["computer_name"];
cnn.Close();

Oracle connection getting time out

I have an application which query database at a specific time of day and then it idle for next 3-4 hours and then again it queries database for some data but it is being executed only once and at the second attempt it is throwing an error.
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = _query;
command.CommandText = sql;
OracleDataAdapter oAdapter = new OracleDataAdapter(sql, connection);
oAdapter.Fill(myDataSet);
connection.Close();
return myDataSet;
}
The Error is being thrown at:
oAdapter.Fill(myDataSet);
And error stats as ORA-03113: end-of-file on communication channel
To my understanding connection should be disposed after one call and it should create another connection on each request. I have checked that the connection to the server is available and listening, no network issues while this error is occurring.
I got it, For any one else looking for answer is that I was calling return myDataSet; inside the using statement first i didn't notice it but as OracleConnection is being inherited from IDisposable and i was returning dataset inside using statement so it was never getting disposed off properly. so i just changed this from
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = _query;
command.CommandText = sql;
OracleDataAdapter oAdapter = new OracleDataAdapter(sql, connection);
oAdapter.Fill(myDataSet);
connection.Close();
return myDataSet;}
to
using (OracleConnection connection = new OracleConnection()){
connection.ConnectionString = connectionString;
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = _query;
command.CommandText = sql;
OracleDataAdapter oAdapter = new OracleDataAdapter(sql, connection);
oAdapter.Fill(myDataSet);
connection.Close(); }
return myDataSet;

Missing Required Parameter in Parameterized Query?

I am getting the following error trying to execute the code below
No Value Given For One Or More Required Parameters.
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = "SELECT [FUNCTION],[NAME] from [Sheet1$] WHERE [FUNTION] = ?";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connString;
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("?", paraName);
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd);
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
OleDbCommand does not support named parameters (see the docs). What you need to do is something like:
cmd.Parameters.Add(new OleDbParameter { Value = paraName });
Edit: I haven't tried it, but I suppose it might be possible to use your above code and pass null as the name argument...
James, I can see that you are trying to parametrize as you would with SQL. However OleDb wouldn't follow the exact pattern. In OleDb you can simply put question marks in your sql sentence and fill them up later using Parameter.Add().value which is quite straight forward.
As MSDN reference points out:
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text.
I have rewritten your code in the way it should look like
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = string.Format("SELECT [{0}],[{1}] from [{2}] WHERE [{0}] = ?", strFunction, strName, strSheetName);
conn.ConnectionString = connString;
using (OleDbConnection conn = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameter.Add("#Param1", OleDbType.VarChar).Value = paraName; // paraName or any value you wish.
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd); //or cmd.ExecuteNonQuery(); in Insert sql commands.
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Note, You should put your OleDbConnection inside the using statement rather than your OleDbCommand.
I haven't tested it and it may contain some minor error. Other than that punch it there and press play (F5).
You can find more on OleDb parametrization from OleDbCommand.Parameters Property
Good luck and let us know what happens.

Using a existing connection in a Script Component (SSIS)

I have am OLEDB Connection configured in the connection managers and I want to use it in a SCRIPT. The script needs to call a stored proc and then create buffer rows. I have added the connection to the connections available to the script and this is my code.
Boolean fireagain = true;
SqlConnection conn = new SqlConnection();
conn = (SqlConnection)(Connections.Connection
.AcquireConnection(null) as SqlConnection);
SqlCommand cmd = new SqlCommand();
conn.Open();
ComponentMetaData.FireInformation(
0, "Script", "Connection Open", string.Empty, 0, ref fireagain);
cmd.Connection = conn;
cmd.CommandText = "up_FullTextParser_select" ;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("Phrase", DbType.String).Value = Row.Keywords;
cmd.Parameters.AddWithValue("SpecialTerm", DbType.String).Value = "Exact match";
cmd.Parameters.AddWithValue("StopListId", DbType.Int32).Value = 0;
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
TermsBuffer.AddRow();
TermsBuffer.Term = rdr[0].ToString();
}
conn.Close();
Anyway, it seems to fail on the AcquireConnection. Am I converting this wrong? Should I be using a different way to using the connections defined outside the script?.
You cannot cast an OLEDB connection to SqlConnection object. You must use the OleDbConnection object. See the example - http://blogs.msdn.com/b/mattm/archive/2008/08/22/accessing-oledb-connection-managers-in-a-script.aspx
This MSDN example implies that you using AcquireConnection incorrectly.
You need to use a managed connection provider.
If you insist on using an OLEDB connection, you cannot use AcquireConnection but you can extract the connection string and then use it to create an OLEDB connection:
string connstr = Dts.Connections["my_OLEDB_connection"].ConnectionString;
System.Data.OleDb.OleDbConnection objConn = new System.Data.OleDb.OleDbConnection(connstr);
This may not work if the connection string is created via an expression of some sort.
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
datatable dtExcelData = new datatable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();

Categories

Resources