'No data exists for the row/column.' Oledb Exception - c#

connection.Open();
OleDbCommand command = new OleDbCommand("SELECT [Names] FROM Test",
connection);
OleDbDataReader reader = command.ExecuteReader();
string result = reader.GetValue(0).ToString();
MessageBox.Show(result);
connection.Close();
Could anyone help? I'm getting 'No data exists for the row/column.' this error thrown

You are not calling Read Method
OleDbDataReader reader = command.ExecuteReader();
if(reader.Read())
{
string result = reader.GetValue(0).ToString();
MessageBox.Show(result);
}
connection.Close();
This will just read the first row from the result.If you want all the rows then you will need to write some thing like this
OleDbDataReader reader = command.ExecuteReader();
List<string> data = new List<string>();
while(reader.Read())
{
data.Add(reader.GetValue(0).ToString());
}
connection.Close();

Related

C# SQL Server database queries

I have written the following code to query stuff from a SQL Server database. The query in the first reader works, but not in the second. I just can't seem to figure out why as the approach is exactly the same in both readers. Any help is much appreciated.
The parameters for the commands are given in the function above which isn't in the code btw.
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "...";
conn.Open();
SqlCommand command = new SqlCommand("SELECT stuff FROM table WHERE Belegnummer= #n and Belegjahr=#j", conn);
command.Parameters.Add(new SqlParameter("n", nr));
command.Parameters.Add(new SqlParameter("j", jahr));
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
r = reader.GetInt32(0);
}
}
command.Dispose();
SqlCommand command2 = new SqlCommand("SELECT stuff1, stuff2, stuff3 FROM sameTable WHERE BelID = #rnr", conn);
command2.Parameters.Add(new SqlParameter("rnr", r));
using (SqlDataReader reader2 = command2.ExecuteReader())
{
while (reader2.Read())
{
// variables are defined somewhere above
b = reader2.GetInt32(0);
j = reader2.GetInt32(1);
m = reader2.GetInt32(2);
}
}
}
Please post the error messages as well.
You may run into trouble with DbNull values. Check for DbNull before you parse the values with:
SqlReader.IsDBNull(column)
Or load the Data into a DataTable:
DataTable dt = new DataTable();
using (SqlDataReader reader = cmd1.ExecuteReader())
{
dt.Load(reader);
}

binding two SQL statements within single Method using ArrayList in (SQL & C#)

i want to show list of SemesterID based on StudentID as shown below.
in comboBox1 i have listed StudentIDs but give me an Errors:
Error #1
Con is not closed.
Error #2
DataReader is Already in use...
public void bindStudentID()
{
try
{
ArrayList a = new ArrayList();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT studentId FROM tbStudent", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
a.Add(dr["studentId"]);
}
comboBox1.DataSource = a;
ArrayList aa = new ArrayList();
SqlCommand cmdd = new SqlCommand("SELECT SemesterID FROM tbSemester Where StudentID='" + comboBox1.Text + "'", con);
SqlDataReader drr = cmd.ExecuteReader();
while (drr.Read())
{
aa.Add(drr["SemesterID"]);
comboBox2.DataSource = aa;
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
You forgot to close the reader like this:
// Call Close when done reading.
reader.Close();
try using this syntax for your connection, it's safer:
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
ReadSingleRow((IDataRecord)reader);
}
// Call Close when done reading.
reader.Close();
}
I think this code will work fine. This code is explains itself. You were creating a SqlDataReader object without disposing previous one.
public void bindStudentID()
{
try
{
ArrayList a = new ArrayList();
con.Open();
SqlCommand cmd = new SqlCommand("SELECT studentId FROM tbStudent", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
a.Add(dr["studentId"]);
}
comboBox1.DataSource = a;
ArrayList aa = new ArrayList();
SqlCommand cmdd = new SqlCommand("SELECT SemesterID FROM tbSemester Where StudentID='" + comboBox1.Text + "'", con);
dr = null;
dr = cmd.ExecuteReader();
while (dr.Read())
{
aa.Add(drr["SemesterID"]);
}
comboBox2.DataSource = aa;
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}
}
Please mark as answer if I helped
check this,
SqlDataReader drr = cmd.ExecuteReader();
it should be
SqlDataReader drr = cmdd.ExecuteReader();
you are using cmd instead of cmdd command
MSDN says:
You should always call the Close method when you have finished using the DataReader object.
If your Command contains output parameters or return values, they will not be available until the DataReader is closed.
Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You cannot execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed.
So based on MSDN, try this:
public void bindStudentID()
{
//instantiating a ArrayList object does not need to be included inside Try/Catch block
//try
//{
ArrayList a = new ArrayList();
try
{
//Before opening the connection make sure that connection's current state is not open, otherwise you will get exception
//con.Open();
if (con.State != ConnectionState.Closed)
{
con.Close();
}
con.Open();
SqlCommand cmd = new SqlCommand("SELECT studentId FROM tbStudent", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
a.Add(dr["studentId"]);
}
comboBox1.DataSource = a;
//You should close data reader before using it again or defining new one
dr.Close();
ArrayList aa = new ArrayList();
//No need to define new SqlCommand object and you can use the prev one
cmd = new SqlCommand("SELECT SemesterID FROM tbSemester Where StudentID='" + comboBox1.Text + "'", con);
//No need to define new SqlDataREader object and you can use the prev one
dr = cmd.ExecuteReader();
while (dr.Read())
{
aa.Add(dr["SemesterID"]);
//I think this should be stated out of the while block
//comboBox2.DataSource = aa;
}
comboBox2.DataSource = aa;
//You should close data reader before using it again or defining new one
dr.Close();
//Close the connection in finally block
//con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
//You should also close the connection even if an exception raised
con.Close();
}
}

SqlDataReader can't read data even though it finds something

As, the title says, SqlDataReader can't read the data it finds. I'm querying a particular table for a username to later use in adding data to another table. The reader finds results (Reader.HasRows is true), but can't read them. This is the code:
Connection.Open();
Command = new SqlCommand("SELECT ID FROM Users WHERE Username = #Username", Connection);
Command.Parameters.Add("#Username", TextBox1.Text);
SqlDataReader Reader = Command.ExecuteReader();
if (Reader.HasRows)
{
var ID = Reader[0];
Reader.Close();
Command = new SqlCommand("INSERT INTO Locations (User_ID,Location,Date) VALUES (#User_ID,#Location,GETDATE())", Connection);
Command.Parameters.Add("#User_ID", ID);
Command.Parameters.Add("#Location", TextBox2.Text);
Command.ExecuteNonQuery();
}
else
{
ErrorLabel.Text = "Username could not be found.";
}
You have to call Reader.Read() in order to advance to the next row.
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
You need to call Read method on reader.
eg.
while (reader.Read())
{
....
}
More info in MSDN.
I Would do this:
while (Reader.HasRows())
{
Reader.Read();
string ID = Reader["ID"].ToString();
...
}
Use if (reader.Read()) instead of if (Reader.HasRows)
Yeah. You never READ.
while (Reader.Read ()) {
}
instead of If hasrows.
You must call Read. Like every tutorial shows.

Read Integer values via Reader.(Sql-server)

con.Open();
cmd = new SqlCommand("USE PRODUCTS SELECT BOUGHT FROM " +
DropDownList1.SelectedItem.Text +
" WHERE ID = #ID", con);
cmd.Parameters.Add("ID", SqlDbType.Int).Value = DropDownList2.SelectedIndex;
int i = cmd.ExecuteReader().GetInt32(0);
con.Close();
I can't read integer values with reader like this. I get runtime error System.InvalidOperationException. What is wrong with my code ? if you can't find the mistake, can you explain how can i read integer values with reader ? By the way this part of code gives the error:
int i = cmd.ExecuteReader().GetInt32(0);
Try this:
int x=0;
using (
SqlConnection connection = new SqlConnection(strCon))
{
SqlCommand command = new SqlCommand(sql_string, connection);
connection.Open();
DataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
x = reader.GetInt32(0);
}
}
reader.Close();
}
You need to initialise a reader and then read it
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read()) // or just rdr.Read() if you know only one row is returned
{
int i = rdr.GetInt32(0);
What I have done to make things a lot easier on my end, since I mainly use SQL all over the place, is make some extensions.
eg
public static Int32 GetInt32(this SqlDataReader rdr, string column)
{
return Convert.ToInt32(rdr[column]);
}

ADO.NET - DataRead Error

I am trying to display data from a column in my database onto my rich textbox, but I am getting mixed up between DataSet and DataReader - I know the majority of the code below is correct, I just get two lines containing errors, and I'm not sure why:
// Create a connection string
string ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= C:\\Documents and Settings\\Harley\\Desktop\\Test.accdb");
string SQL = "SELECT * FROM Paragraph";
// create a connection object
SqlConnection conn = new SqlConnection(ConnectionString);
// Create a command object
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt); //ERROR
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
foreach(DataRow reader in dsRtn) //ERROR
{
richTextBox = richTextBox.Text + reader[0].ToString();
}
//Release resources
reader.Close();
conn.Close();
}
Each of your snippets has an issue.
For the Data Adapter implementation you provided this:
SqlCommand cmd = new SqlCommand(SQL, conn);
conn.Open();
DataTable dt = new DataTable();
da.Fill(dt); //ERROR
You are not associating your SqlCommand object with your DataAdapter so it has no idea how to fill your DataTable.
As for your Data Reader implementation,
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
foreach(DataRow reader in dsRtn) //ERROR
{
richTextBox = richTextBox.Text + reader[0].ToString();
}
you are using the DataReader incorrectly try this:
// Call ExecuteReader to return a DataReader
SqlDataReader reader = cmd.ExecuteReader();
while( reader.Read() )
{
richTextBox = richTextBox.Text + reader[0].ToString();
}

Categories

Resources