ADO.NET - DataRead Error - c#

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();
}

Related

How do I clone data from a SqlDataReader keeping all Columns and Rows in a way that can be exported through a method?

I'm currently trying to create a method that allows me to run any query on a connectionstring, and get the results returned in a readable way for my ASP.Net website. Because I need access to all rows and columns a query might need, I cannot simply return a string or an array of strings. If I return a SqlDataReader, I'm not able to read the data outside of the method, because the connection is closed.
This is what my method currently looks like.
private SqlDataReader QueryConnectionString (string query)
{
// New SQL Connection
SqlConnection cnn;
// New Connection String
string connetionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
// Instantiate the SQL Connection with Connection String
cnn = new SqlConnection(connetionString);
// Create a SqlCommand with the input Query
SqlCommand command = new SqlCommand(query, cnn);
cnn.Open();
// Create a SqlDataReader and tie it to the query
SqlDataReader reader = command.ExecuteReader();
cnn.Close();
return reader;
}
In my other methods I would have something like this
SqlDataReader reader = QueryConnectionString("SELECT * FROM tTable");
lblOutput.Text = reader.GetString(0);
But doing so gives me the error
System.InvalidOperationException: 'Invalid attempt to call
CheckDataIsReady when reader is closed.'
I realize that returning a SqlDataReader is not an option. What can I return the data as so that other methods can read the data?
You can return a DataTable which will preserve the columns and rows of the query. Instead of a SqlDataReader consider using SqlDataAdapter. One advantage is that the Fill method of SqlDataAdapter will open and close the connection for you.
var dt = new DataTable();
using (var da = new SqlDataAdapter(query, cnn))
{
da.Fill(dt);
}
Your full method might look something like this:
private DataTable GetData(string query)
{
// New Connection String
string connetionString = ConfigurationManager.ConnectionStrings["ConnectionStringName"].ConnectionString;
// Instantiate the SQL Connection with Connection String
SqlConnection cnn = new SqlConnection(connetionString);
// declare datatable
var dt = new DataTable();
// create SqlDataAdapter
using (var da = new SqlDataAdapter(query, cnn))
{
// fill datatable
da.Fill(dt);
}
return dt;
}
You will then need to read from the DataTable. See my answer here for a method to read data. The method in the linked answer uses the Field<T> extension from DataSetExtensions to extract data. Please see example below:
// get data from your method
DataTable table = GetData("select * from MyTable");
// iterate over the rows of the datatable
foreach (var row in table.AsEnumerable()) // AsEnumerable() returns IEnumerable<DataRow>
{
var id = row.Field<int>("ID"); // int
var name = row.Field<string>("Name"); // string
var orderValue = row.Field<decimal>("OrderValue"); // decimal
var interestRate = row.Field<double>("InterestRate"); // double
var isActive = row.Field<bool>("Active"); // bool
var orderDate = row.Field<DateTime>("OrderDate"); // DateTime
}
To check if a DataTable is null/ empty see this answer. It can be as simple as:
if(table?.Rows?.Count() > 0) { ... }
You can try this
IEnumerable<IDataRecord> GetRecords()
{
using(var connection = new SqlConnection(#"..."))
{
connection.Open();
using(var command = new SqlCommand(#"...", connection);
{
using(var reader = command.ExecuteReader())
{
while(reader.Read())
{
// your code here.
yield return reader;
}
}
}
}
}

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

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();

Asp.net I have to export data in excel

if (!IsPostBack)
{
OracleConnection conn = new OracleConnection(conns); // C#
OracleCommand cmd = new OracleCommand("select * from APPLICATION AND FRAME", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
OracleDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
grdSeacrhResult.DataSource = dt;
grdSeacrhResult.DataBind();
conn.Close();
}
got error of
ORA-00933: SQL command not properly ended.
Once you have sorted your SQL out use Nuget and get closedXML,
then your code should be
private void WriteExcelData(string f, DataTable dt, string savePath, string sheetName)
{
using (wb == new XLWorkbook(f))
{
dynamic ws = wb.Worksheet(sheetName);
ws.Cell(1, 1).InsertTable(dt.AsEnumerable());
wb.SaveAs(savePath);
}
}
or if you want to use the closed XML documentation use this https://closedxml.codeplex.com/wikipage?title=Adding%20DataTable%20as%20Worksheet&referringTitle=Documentation

How to display a specific data from a database into textbox?

public DataTable DisplayHolidays(int empid)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("ComputeHoliday", myCon);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmployeeID", SqlDbType.Int).Value = empid;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
temp2 = rd[0].ToString();
}
return dt;
}
This is my code I had a problem/error with this part. This code is in the class not in the form load. It cannot display the data in the textbox. I'm using temp2 to store the data in the selected row but it's not yet working.
I assume that you're getting an exception at cmd.ExecuteReader().
Note that you must open the connection before you can use the command in cmd.ExecuteReader(). DataAdapter.Fill does not need an open connection, the dataadapter will open/close it implicitly.
MSDN:
The connection object associated with the SELECT statement must be
valid, but it does not need to be open. If the connection is closed
before Fill is called, it is opened to retrieve data, then closed. If
the connection is open before Fill is called, it remains open.
Why do you use DataAdapter.Fill(DataTable) and also Command.ExecuteReader? You need just one way to get the data. If you already have filled a table:
If(dt.Rows.Count > 0)
{
temp2 = dt.Rows[0].Field<string>(0);
}
If you don't use the DataAdapter and the DataTable but only the reader:
using(SqlDataReader rd = cmd.ExecuteReader())
{
if(rd.HasRows)
{
rd.Read();
temp2 = rd.GetString(0);
}
}

Oracle database table in gridview

I want to get the result from a query in my oracle database and put it in a gridview. Now my problem is, I have no idea how to output it in the gridview. I am using the gridview from the toolbox and my oracle connection is working. I also have the right SELECT query and I can output that in a listbox. I just have no idea how to do this in a gridview. I looked for it and I came across this: How to populate gridview with mysql? Although this doesn't help me.
How can I output it in a gridview so that it looks exactly the same as a normal table in the oracle database?
What should I use and how?
This is my code:
public void read()
{
try
{
var conn = new OracleConnection("")
conn.Open();
OracleCommand cmd = new OracleCommand("select * from t1", conn);
OracleDataReader reader = cmd.ExecuteReader();
DataTable dataTable = new DataTable();
while (reader.Read())
{
var column1 = reader["vermogen"];
column = (column1.ToString());
listBox1.Items.Add(column);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
To bind a DataTable to a DataGridView your code need simply to be changed to
public void read()
{
try
{
using(OracleConnection conn = new OracleConnection("....."))
using(OracleCommand cmd = new OracleCommand("select * from t1", conn))
{
conn.Open();
using(OracleDataReader reader = cmd.ExecuteReader())
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The OracleDataReader could be passed to the Load method of the DataTable and then the table is ready to be bound to the DataGridView DataSource property. I have also added some using statement to ensure proper disposing of the disposable objects employed. (In particular the OracleConnection is very expensive to not close in case of exceptions)
You can use DataSet too:
public void read()
{
try
{
OracleConnection conn = new OracleConnection("");
OracleCommand cmd = new OracleCommand("select * from t1", conn);
conn.Open();
cmd.CommandType = CommandType.Text;
DataSet ds = new DataSet();
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
First establish connection in case, you didnt establish globally by using connection string. Then use oleDbcommand for the oracle sql command you want to execute. In my case, it is 'select * from table_name' which would show all data from table to datagrid. I wrote this code in a button to display data on data grid.
{
OleDbConnection conn = new OleDbConnection("");
OleDbCommand cmd = new OleDbCommand("select * from table_name", conn);
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
{
DataTable dataTable = new DataTable();
dataTable.Load(reader);
dataGridView1.DataSource = dataTable;
}
conn.Close();
}
}

Categories

Resources