Loading Access DB Table to Datatable - c#

I have a database in .ACCDB format with some tables.
I'm successfully loading it into an OleDbDataReader with the following code:
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\marcelo.accdb";
OleDbConnection conn = new OleDbConnection(connectionString);
string sql = "SELECT * FROM Clientes";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
OleDbDataReader reader;
reader = cmd.ExecuteReader();
I'd like to load the table "clientes" to a datatable instead. How should I do it ?

string connString =
"Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\\marcelo.accdb";
DataTable results = new DataTable();
using(OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("SELECT * FROM Clientes", conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
}

Related

How to convert Ods file to Data Set C#

I am unable to convert ods file to data set
I have downloaded the file from follwoing link
UK List ods file link
and using following piece of code to convert this ods file to data set
int count = 0;
int list_clear = 1;
string connectionString;
if (ConfigurationManager.AppSettings["OperatingSystem"] == "64Bits")
connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + location + ";Extended Properties=\"Excel 12.0;\"";
else
connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
location + #";Extended Properties=""Excel 8.0;HDR=YES;""";
int recCount = 0;
string xmlData = "";
// Create a factory
DbProviderFactory factory =
DbProviderFactories.GetFactory("System.Data.OleDb");
// Create an adapter
DbDataAdapter adapter = factory.CreateDataAdapter();
// Create a select command to get the dataset
DbCommand selectCommand = factory.CreateCommand();
//selectCommand.CommandText = "SELECT * FROM [sanctionsconlist$]";
selectCommand.CommandText = "SELECT * FROM [sheet1$]";// "SELECT * FROM [Data$]";
// Set up the connection and the connection string
DbConnection connection = factory.CreateConnection();
connection.ConnectionString = connectionString;
selectCommand.Connection = connection;
// Set up the command
adapter.SelectCommand = selectCommand;
// Create the dataset
DataSet ds = new DataSet();
DataSet dsData = new DataSet();
// Load the results
adapter.Fill(ds);
con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStringName"].ConnectionString);
cmd = new SqlCommand();
con.Open();
tran = con.BeginTransaction();
cmd.CommandText = "USP_ImportUKListSanctionListData";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Transaction = tran;
cmd.Parameters.Add("#xmlData", SqlDbType.NVarChar, -1);
cmd.Parameters.Add("#list_clear_flag", SqlDbType.Int);
cmd.Parameters.Add("#update_list", SqlDbType.Int);
cmd.Parameters.Add("#Error", SqlDbType.Int);
DataTable dt = ds.Tables[0].Clone();
but i get the error, external table is not in the expected format
Can any one help me in this reagard, thanks

Im trying to load and display a table from sql into my datagrid in C# but its not displaying

//instantiating connection
dbConn = new SqlConnection("Data Source = local host; initial catalog=Project; Integrated Security = SSPI ");
ds = new DataSet();
//select everything from the table
dbCommand = new SqlCommand("SELECT * FROM Shops;", dbConn);
dbAdapter = new SqlDataAdapter(dbCommand);
//filling the datagrid
dbAdapter.Fill(ds, "All Shops");
dataGridView1.DataSource = ds.Tables["All Shops"];
To show data into datagrid you need to assign datasource and then use DataBind() to bind the data.
dataGridView1.DataSource = ds.Tables["All Shops"];
dataGridView1.DataBind(); // use this after assigning the datasource
private void GetResults()
{
//Establishing the MySQL Connection
MySqlConnection conn = new MySqlConnection("Database=potentiality_live;Data Source=eu;User Id=ptly;Password=phat40");
string query;
MySqlCommand SqlCommand;
MySqlDataReader reader;
MySqlDataAdapter adapter = new MySqlDataAdapter();
//Open the connection to db
conn.Open();
//Generating the query to fetch the contact details
query = "SELECT id,date_time,link FROM'sdfsdfsdf'";
SqlCommand = new MySqlCommand(query, conn);
adapter.SelectCommand = new MySqlCommand(query, conn);
//execute the query
reader = SqlCommand.ExecuteReader();
//Assign the results
GridView1.DataSource = reader;
//Bind the data
GridView1.DataBind();
}
Reference:
http://www.codeproject.com/Questions/453091/how-to-get-data-from-sql-database-to-gridview-by-c

Error in filling dataset with oledb

I am getting
"No value given for one and more required parameter"
from below code everything looks fine not able to find the problem.
string myConnectionString= #"Provider=Microsoft.Jet.OLEDB.4.0; Data source=D:\TiptonDB.mdb";
string query = "SELECT NodeID FROM NDDINodes";//"SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
DataSet dt = new DataSet();
using (OleDbConnection myConnection = new OleDbConnection())
{
myConnection.ConnectionString=myConnectionString;
OleDbCommand cmd=new OleDbCommand ();
cmd.Connection=myConnection;
// cmd.CommandText="SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
myConnection.Open();
OleDbDataAdapter ad = new OleDbDataAdapter(query,myConnection);
ad.Fill(dt);
}
string myConnectionString= #"Provider=Microsoft.Jet.OLEDB.4.0; Data source=D:\TiptonDB.mdb";
string query = "SELECT NodeID FROM NDDINodes";//"SELECT O.NodeID, N.NodeID FROM NDDINodes AS N, NDDINodes AS O WHERE N.X=O.X And N.Y=O.Y And N.NodeID<>O.NodeID";
DataSet dt = new DataSet();
OleDbConnection objXConn = new OleDbConnection(myConnectionString);
objXConn.Open();
OleDbCommand objCommand = new OleDbCommand(query, objXConn);
OleDbDataAdapter adp = new OleDbDataAdapter(objCommand);
adp.Fill(dt);
objXConn.Close();
Make sure your connection string isn't missing data: UserName/Password, Persist Security Info=True,...
Check this link for access connectionString settings.
just add this in your code
OleDbDataAdapter ad = new OleDbDataAdapter();
ad.SelectCommand = new OleDbCommand(query, myConnection);

How to View Data from MS Access in Data Grid View?

I am new in C-Sharp, i am trying to access my Database from C-Sharp, i have written the following code, and i dont know what to write next to view data. I have searched this on net but didnt get much. Kindly tell me this in easy code.
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbConnection conn = new OleDbConnection(connection);
conn.Open();
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.SelectCommand = cmd;
Refer following code:
string strProvider = "#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
string strSql = "Select * from score";
OleDbConnection con = new OleDbConnection(strProvider);
OleDbCommand cmd = new OleDbCommand(strSql, con);
con.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable scores = new DataTable();
da.Fill(scores);
dataGridView1.DataSource = scores;
Hope its helpful.
Try this
try
{
Dataset myDataSet=new Dataset();
string connection = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Database3.accdb";
OleDbCommand cmd = new OleDbCommand("Select * from score", conn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(cmd );
connection .Open();
myDataAdapter.Fill(myDataSet,"TableName");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
return;
}
finally
{
connection .Close();
}
Remember for good coding practice ,always connection should be open in Try Block
and closed in Finally Block

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