Unable to load OleDbDataReader to DataTable - c#

I am reading data from MS access 2010 file. I am using OleDbDataReader to read the data which is working but when I am unable to load that in DataTable .
Code:
DataTable dt = new DataTable();
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\My Stuff\AjaxTest & Test porjects\WbsiteWithAccessDataConnectivity\WbsiteWithAccessDataConnectivity\App_Data\Northwind 2010.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("Select * from Customers", conn))
{
using (OleDbDataReader rd = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
{
dt.Load(rd); // Unable to load
rd.Close();
}
conn.Close();
}
}
return dt;
Any suggestions?

I'm not exactly sure if you are getting an error or what is happening with your code but my suggestion would be to add LoadOption and/or errorHandler parameters to find out exactly what is happening.
dt.Load(rd,OverwriteChanges); // Unable to load
More info here. https://msdn.microsoft.com/en-us/library/hsze9wte%28v=vs.110%29.aspx

Related

SSIS Script Task Error. Fill: SelectCommand.Connection property has not been initialized

I have been attempting this several different ways based on searches I have found online but am having the same result.
I am working on an SSIS Script Task that will execute a stored procedure that needs a TVP parameter to be passed into it. I have all that wired up and working properly, but when it gets to the da.Fill(resultDT)
I get the error:
Fill: SelectCommand.Connection property has not been initialized.
OleDbDataAdapter A = new OleDbDataAdapter();
DataTable dt = new DataTable();
A.Fill(dt, Dts.Variables["User::Companies"].Value);
DataTable resultDT = new DataTable();
using (SqlConnection sqlcon = (SqlConnection)(Dts.Connections["RegistryConnection"].AcquireConnection(Dts.Transaction) as SqlConnection))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = sqlcon;
cmd.CommandText = "[Registry].[GetClientData_ByCompanyIDs]";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#companyIDs", dt);
using (SqlDataAdapter da = new SqlDataAdapter())
{
da.SelectCommand = cmd;
da.Fill(resultDT);
Dts.Variables["User::Clients"].Value = resultDT;
}
}
}
Any ideas what I am missing? Hoping it's something easy that I am overlooking.
Issue was that I was using an OLEDB Connection Manager, which apparently cannot be cast to an SQLConnection in the way I was doing it.
Needed to setup ADO.Net Connection Manager and then the SQLConnection cast worked as intended.
Problem Solved.

The specified method is not supported

I'm working on a program that shows in a chart in asp.net two columns of a table, so I made a connection to my database (which is correct), the problem is in the metudo (Chart1.DataBindTable) that does not Is working And gives the following error: The specified method is not supported.
I was very grateful if anyone helped me.
The code:
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas] GO", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
Chart1.DataBindTable(rdr, " Consumo_Medio_Real");
Remove that GO from your SQL statement. Your SQL statement should looks like
SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas]
Well you are getting error cause the specified column name has space in it as can be seen below
Chart1.DataBindTable(rdr, " Consumo_Medio_Real");
^... Here
It should rather be like below cause the column name represents the X-Axis
Chart1.DataBindTable(rdr, "Consumo_Medio_Real");
See below MSDN link for an example
https://msdn.microsoft.com/en-us/library/dd456766.aspx
Try without "GO"
string cs = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("SELECT [Consumo_Medio_Real], [Tipo_de_Fatura] FROM [dbo].[t_faturas]", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
//Add datatable...
System.Data.DataTable dt = new DataTable();
dt.Load(rdr);
var enumerableTable = (dt as System.ComponentModel.IListSource).GetList();
chart1.DataBindTable(enumerableTable , "X");
And try dumping the data into some objet that implement ienumerable... and pass that as the parameter to .DataBindTable()
look the definition here (the SqlDataReader does not implement IEnumerable)
hope this help!

Fill data table using access - C#

I built a connection string to access data from a database to fill a datatable.
connectionname = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=d:\\projects\\checking.mdb; OLE DB Services=-1"
DataTable results = new DataTable();
using (OleDbConnection thisConnection = new OleDbConnection(connectionname))
{
OleDbCommand cmd = new OleDbCommand("SELECT * from PatTestTable", thisConnection);
thisConnection.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}
There is no error and in the debug mode, I can see the connection string being built correctly but the results datatable is empty. Did I miss any step?

There is already an open DataReader associated with this Connection which must be closed first using c#

I am getting this error "There is already an open DataReader associated with this Connection which must be closed first". I have tried using command but still can't fix this issue. The code I am using is as follows
{
conn.Open();
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
using (MySqlDataAdapter MyAdapter = new MySqlDataAdapter())
{
MyAdapter.SelectCommand = cmd;
using (DataTable dTable = new DataTable())
{
MyAdapter.Fill(dTable);
GridView1.DataSource = dTable;
}
}
}
I was originally trying below code (without using command).
conn.Open();
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
cmd.ExecuteReader();
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = cmd;
DataTable dTable = new DataTable();
MyAdapter.Fill(dTable);
GridView1.DataSource = dTable;
conn.Close();
But both of the codes are giving exactly the same error (i.e. There is already an open DataReader associated with this Connection which must be closed first.)
Your help would be really appreciated.
Thanks in advance!
Usage of dataset will be more handy and efficient rather than table.Even you can cache it.
Also no need to use using construct because MySqlAdapter's fill method does it everything for you like
i)Open the connection. ii)Read the command ii)Execute the command ii)close the connection
using ()
{
if(Cache["mydata"]==null)
{
queryStr = "";
queryStr = "select * from mydata.items;";
cmd = new MySqlCommand(queryStr, conn);
MySqlDataAdapter MyAdapter = new MySqlDataAdapter();
MyAdapter.SelectCommand = cmd;
DataSet ds =new DataSet();
MyAdapter.Fill(ds);
Cache["mydata"]=ds;
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
GridView1.DataSource = (DataSet)Cache["mydata"];
GridView1.DataBind();
}
}
This line creates a DataReader that you're not closing:
cmd.ExecuteReader();
Just remove the whole line, it's useless in your case.

Problem reading excel sheet

SqlDataReader reader;
string r="";
if ((FileUpload1.PostedFile != null)&&(FileUpload1.PostedFile.ContentLength > 0))
{
r = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
}
OleDbConnection oconn =
new OleDbConnection
(#"Provider=Microsoft.Jet.OLEDB.4.0;"
+ #"Data Source="+r+";"
+ #"Extended Properties=""Excel 8.0;HDR=Yes;""");
oconn.Open();
OleDbCommand dbcom = new OleDbCommand("SELECT * FROM [Sheet1$]", oconn);
OleDbDataReader dbreader = dbcom.ExecuteReader();
int rni = dbreader.GetOrdinal ("RollNo");
int mki = dbreader.GetOrdinal ("marks");
Here the program works only if the excel sheet is present in the project folder. And if any changes are made to the excel sheet and then the program is run again, then only the rows that were present before are fetched, and not the ones added later. Please help me.....thanks in advance.....
Hi Please post the complete code, alternatively you can import the complete worksheet to a Datatable object with the below method and retrieve required columns and rows of DataTable
static public DataTable ExecuteOleDataTable(string sql, string oledbconnectionstring)
{
using (OleDbCommand command = new OleDbCommand())
{
command.CommandType = CommandType.Text;
OleDbConnection oledbconnection = new OleDbConnection(oledbconnectionstring);
command.Connection = new OleDbConnection(oledbconnectionstring); ;
command.CommandText = sql;
if (oledbconnection.State == System.Data.ConnectionState.Open)
oledbconnection.Close();
oledbconnection.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(command);
DataTable datatable = new DataTable();
sda.Fill(datatable);
oledbconnection.Close();
return datatable;
}
}

Categories