exception in acquiring data - C# with OracleDB - c#

static public void ConnectAndQuery()
{
string connectionString = GetConnectionString();
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
Console.WriteLine("State: " + conn.State);
Console.WriteLine("Connection String: " + conn.ConnectionString);
OracleCommand command = conn.CreateCommand();
string sql = "SELECT * FROM users";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
The connection is established and working open but I get IndexOutOfRangeException when trying to acquire the data from the DB. The exception is caught on
string myField = (string)reader["MYFIELD"];
I looked for info about the OracleDataReader and the command in order to understand the reader, but... does it store the data acquired in an array or any other sequence ? Why am I getting the IndexOutOfRangeException and why does the reader require an argument in the [] brackets?

You probably do not have a field that is called MYFIELD. Remember that the field names are case sensitive... Try using an index instead i.e. reader[0]

Related

"There is already an open DataReader associated with this Command which must be closed first."

I'm working on application which needs to connect to another database to get some data,
and to do that, I decided to use SqlConnection, reader etc..
And I need to execute few queries, for example first I need to get CARD ID for some user, after that I need to get some data by that CARD ID..
Here is my code:
#region Connection to another Database
SqlConnection sqlConnection1 = new SqlConnection("Data Source=ComputerOne; Initial Catalog=TestDatabase;Integrated Security=False; User ID=test; Password=test123;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "Select * From Users Where CardID=" + "'" + user.CardID + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
string cardID = "";
string quantity="";
while (reader.Read())
{
cardID = reader["CardID"].ToString();
}
//HOW COULD I WRITE ANOTHER QUERY NOW, FOR EXAMPLE, OK I GOT CARDID NOW GIVE ME SOME OTHER THINGS FROM THAT DATABASE BY THAT cardID
//here I tried to change CommandText and to keep working with reader.. but its not working like this because its throwing me exception mention in question title.
cmd.CommandText = "Select T1.CardID, T2.Title, Sum(T1.Quantity) as Quantity From CardTransactions as T1 JOIN Adds as T2 ON T1.AddsID = T2.AddsID Where T1.CardID =" + cardID + "AND T1.Type = 1 Group By T1.CardID, T2.Title";
reader = cmd.ExecuteReader();
while (reader.Read())
{
quantity = reader["Quantity"].ToString();
}
// Data is accessible through the DataReader object here.
sqlConnection1.Close();
#endregion
So guys how could I execute few queries statemens using this example.
Thanks a lot!
Cheers
Your problem is that you are not disposing the objects you are using. For that purpose is better to always use using structure, since it will guarantee you that everithing is gonna be disposed. Try the code below:
SqlConnection sqlConnection1 = new SqlConnection("Data Source=ComputerOne; Initial Catalog=TestDatabase;Integrated Security=False; User ID=test; Password=test123;");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
string cardID = "";
string quantity="";
using(sqlConnection1 = new SqlConnection("Data Source=ComputerOne; Initial Catalog=TestDatabase;Integrated Security=False; User ID=test; Password=test123;"))
{
sqlConnection1.Open();
using(cmd = new SqlCommand())
{
cmd.CommandText = "Select * From Users Where CardID=" + "'" + user.CardID + "'";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
cardID = reader["CardID"].ToString();
}
} //reader gets disposed right here
} //cmd gets disposed right here
using(cmd = new SqlCommand())
{
cmd.CommandText = "Select T1.CardID, T2.Title, Sum(T1.Quantity) as Quantity From CardTransactions as T1 JOIN Adds as T2 ON T1.AddsID = T2.AddsID Where T1.CardID =" + cardID + "AND T1.Type = 1 Group By T1.CardID, T2.Title";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
using(reader = cmd.ExecuteReader())
{
while (reader.Read())
{
quantity = reader["Quantity"].ToString();
}
} //reader gets disposed right here
} //cmd gets disposed right here
sqlConnection1.Close();
} //sqlConnection1 gets disposed right here
The reader you opened is still active and open. And you can have just one active reader at a time. You should wrap all Sql... instances in a using to ensure they get closed properly.
using (SqlConnection connection = new SqlConnection(...))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
// the code using reader
}
}
well ... you receive the error because the used reader for the first call was not closed. You should always call the Close method when you have finished using the DataReader object insuring that the connection used by the reader is returned to the connection pool (the connection is in use exclusively by that DataReader). Partial code:
reader = cmd.ExecuteReader();
try
{
while(myReader.Read())
{
while (reader.Read())
{
cardID = reader["CardID"].ToString();
}
}
finally
{
myReader.Close();
}
...
reader = cmd.ExecuteReader();
try
{
while(myReader.Read())
{
reader = cmd.ExecuteReader();
while (reader.Read())
{
quantity = reader["Quantity"].ToString();
}
}
}
finally
{
myReader.Close();
myConnection.Close();
}
Also... as a clean code rule, separate your calls in different methods (SOLID principles)

Connect to remote oracle database using odac

I need to make asmx web service. I installed ODAC from here
Then, i add references to my project:
1) Oracle.DataAccess
2) Oracle.Web
[WebMethod]
public string EaaTest(string r_object_id)
{
string connString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)" +
"(HOST=my host)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=dcmt)));" +
"User Id=my id ;Password=my password;"
using (OracleConnection conn = new OracleConnection(connString))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = string.Format("select DSS_TITLE_RU from DBREP36.DDT_DA_DIRECTION_S where R_OBJECT_ID=0", r_object_id);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
string result = dr.GetString(0);
return result;
}
}
Now, i have exception:
An exception of type 'System.InvalidOperationException' occurred in
Oracle.DataAccess.dll but was not handled in user code
Additional information: Connection must be open for this operation
On line: OracleDataReader dr = cmd.ExecuteReader();
Error message isn't clear at all?
Connection must be open for this operation
You need to open your connection before you execute your command.
conn.Open();
OracleDataReader dr = cmd.ExecuteReader();
Use using statement to dispose your command and reader as you did for your connection.
By the way, you didn't specify zero index in your string.Format. Your
where R_OBJECT_ID=0
should be
where R_OBJECT_ID = {0}
As a better option, use parameterized queries. Any kind of string concatenations are open for SQL Injection attacks.
Since you return just first column of the first row, use ExecuteScalar instead which is exactly what this for.
using(var conn = new OracleConnection(connString))
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = #"select DSS_TITLE_RU from DBREP36.DDT_DA_DIRECTION_S
where R_OBJECT_ID = #id";
cmd.Parameters.AddWithValue(#id, r_object_id);
conn.Open();
return (string)cmd.ExecuteScalar();
}

SQl from concatenation to parameters

I have this sql connection with concatenated strings query and I would like to change it to parameters. I am starting coding on my own and I do not have many reference. Tried googling around but I have not found something clear enough to me.
public bool DBAuthenticate(string strUsername, string strPassword)
{
string sqlstring;
sqlstring = "SELECT * FROM credentials WHERE [Username]='" + strUsername + "' AND [Password]='" + strPassword + "'";
string getconnstring = ConfigurationManager.ConnectionStrings["WTAConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(getconnstring);
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sqlstring,conn);
System.Data.SqlClient.SqlDataReader reader;
conn.Open();
reader = comm.ExecuteReader();
if (reader.Read())
return true;
else
return false;
}
can someone please show me how to modify the code to change the query from concatenation to parameters? Thank you a lot.
In order to use parameters, you need to change your statement as follows:
SELECT * FROM credentials WHERE [Username]=#username AND [Password]=#password
It then contains two parameters (#username and #password) that you need to provide the values for in the command. You can do this with the AddWithValue method:
// ...
System.Data.SqlClient.SqlCommand comm = new System.Data.SqlClient.SqlCommand(sqlstring,conn);
comm.Parameters.AddWithValue("#username", strUsername);
comm.Parameters.AddWithValue("#password", password);
System.Data.SqlClient.SqlDataReader reader;
// ...
Please also note that you should always dispose the connection, commands and readers reliably, so adding some using blocks will help:
using(SqlConnection conn = new SqlConnection(getconnstring))
{
conn.Open();
using(SqlCommand comm = new System.Data.SqlClient.SqlCommand(sqlstring,conn))
{
// ...
using(SqlDataReader reader = comm.ExecuteReader())
{
// ...
}
}
}
Try this one:
sqlstring = "SELECT * FROM credentials WHERE [Username]=#UserName AND [Password]=#Password";
After the declaration of comm object, write this:
comm.Parameters.Add(new SqlParameter(#UserName,strUsername));
comm.Parameters.Add(new SqlParamter(#Password,strPassword);

C# update statement with extract

I get error message :
IErrorInfo.GetDescription failed with E_FAIL(0x80004005)
I think in the code is not any variable that needs [] or?
I was searching and everybody has something to do with [].
string queryString = "SELECT sum(skupaj) FROM cas where sifra = " + textBox1.Text + " and EXTRACT(MONTH FROM Datum) = "+textBox2.Text+"";
try
{
OleDbConnection conn = GetConnection();
OleDbCommand command = new OleDbCommand(queryString, conn);
conn.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
ure = reader.GetValue(0).ToString(); ;
}
reader.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if you just want a sum of something, you dont need a datareader. simply do this:
try
{
OleDbConnection conn = GetConnection();
OleDbCommand command = new OleDbCommand(queryString, conn);
conn.Open();
int count = (Int32) command.ExecuteScalar();
conn.Close();
}
Try to put the table name inside a square bracket like [CAS]. This kind of problem happens if you are using a reserved word in ODBC sql or you are using a field that has space in between then you have to put the field inside a pair of ticks like 'field name'.

C# MySql Storing multiple database rows in C#

I'm struggling a bit with this. I want to get the list of ids from the database where a certain value is equal to a certain value in the row. This call will likely return multiple ids. I want to store the value in the ids returned in a list or arraylist in the c# code but I am finding this troublesome. I have the code up to here:
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader reader;
command.CommandText = "SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers + "";
connection.Open();
reader = command.ExecuteReader();
Any help would be much appreciated
string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];
MySqlConnection connection = new MySqlConnection(strConnection);
List<string> array = new List<string>();
using (MySqlCommand cmd = new MySqlCommand("SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers, connection))
{
try
{
using (MySqlDataReader Reader = cmd.ExecuteReader())
{
while (Reader.Read())
{
array.Add(Reader["idprojects"].ToString());
}
}
}
catch (Exception ex)
{
throw;
}
}
string[] ret= array.ToArray();

Categories

Resources