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;
}
}
Related
I want to insert data directly in the cells of a datagrid and then send it to the database , but the rows are not being added with data, they remain empty after the insertion, despite the data appears in the cells.value when I run the code line by line using F11. The database is well linked to the datagrid because when I use textboxes to put the data in the datagrid cells, it works, but it doesn´t work when I put data directly in the cells, through the following code:
public void BD_Conexao()
{
try
{
OdbcConnection con = new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=xxxx; database=lic; uid=estagio; password=1234; option = 3 ");
con.Open();
}
catch (Exception ex)
{
Console.WriteLine("Erro na ligação à base de dados. \n{0}", ex.Message);
return;
}
}
public void Consulta()
{
con = new OdbcConnection("driver= {MySQL ODBC 5.1 Driver};server=xxxx; database=lic; uid=estagio; password=1234; option = 3 ");
con.Open();
OdbcCommand Command = con.CreateCommand();
Command.CommandText = "select lojas.Id, lojas.NIF, lojas.Loja, lojas.Bloqueado, lojas.DataFim, lojas.lastupdate, lojas.Nome";
Command.CommandType = CommandType.Text;
Command.Connection = con;
OdbcDataAdapter adapter = new OdbcDataAdapter();
adapter.SelectCommand = Command;
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
grid_lic.DataSource = dataSet;
grid_lic.DataMember = dataSet.Tables[0].TableName;
}
private void bt_preencher_Click(object sender, EventArgs e)
{
BD_Conexao();
string DataFim = dateTimePicker.Value.ToString("yyyy-MM-dd");
string lastupdate = dateTimePicker2.Value.ToString("yyyy-MM-dd");
Commandtext = "insert into lojas (NIF,Loja,bloqueado, DataFim, lastupdate, Nome) values (#NIF,#Loja,#Bloqueado,#DataFim,#lastupdate,#Nome)";
OdbcCommand Command = new OdbcCommand(Commandtext, con);
Command.CommandType = CommandType.Text;
Command.Parameters.AddWithValue("#NIF", grid_lic.CurrentRow.Cells[1].Value);
Command.Parameters.AddWithValue("#Loja", grid_lic.CurrentRow.Cells[2].Value);
Command.Parameters.AddWithValue("#Bloqueado", checkBox_bloq.Checked);
Command.Parameters.AddWithValue("#DataFim", grid_lic.CurrentRow.Cells[4].Value);
Command.Parameters.AddWithValue("#lastupdate", grid_lic.CurrentRow.Cells[5].Value);
Command.Parameters.AddWithValue("#Nome", grid_lic.CurrentRow.Cells[6].Value);
Command.ExecuteNonQuery();
Consulta();
}
What is wrong?
data gird needs a data source property to fill data, so :
1) Insert all the data in database with your insert statement.
2) Then you need to do something like this to bind your data from database:
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Authors";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds);
connection.Close();
dataGridView1.DataSource = ds;
How to import the data from an Excel sheet into SQL Server database in asp net?
Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;")
Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon)
Dim objAdapter1 As New OleDbDataAdapter(cmd)
OleDbcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()
Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True"
' Bulk Copy to SQL Server
Dim bulkInsert As New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "Table name"
bulkInsert.WriteToServer(dr)
OleDbcon.Close()e here
Break this down into two steps:
1) Save the file somewhere - it's very common to see this:
string saveFolder = #"C:\temp\uploads"; //Pick a folder on your machine to store the uploaded files
string filePath = Path.Combine(saveFolder, FileUpload1.FileName);
FileUpload1.SaveAs(filePath);
Now you have your file locally and the real work can be done.
2) Get the data from the file. Your code should work as is but you can simply write your connection string this way:
string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath);
You can then think about deleting the file you've just uploaded and imported.
To provide a more concrete example, we can refactor your code into two methods:
private void SaveFileToDatabase(string filePath)
{
String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";
String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
//Create Connection to Excel work book
using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
{
//Create OleDbCommand to fetch data from Excel
using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
{
excelConnection.Open();
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
{
//Give your Destination table name
sqlBulk.DestinationTableName = "Excel_table";
sqlBulk.WriteToServer(dReader);
}
}
}
}
}
private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{
string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);
fileUploadControl.SaveAs(filePath);
return filePath;
}
You could simply then call SaveFileToDatabase(GetLocalFilePath(#"C:\temp\uploads", FileUpload1));
Consider reviewing the other Extended Properties for your Excel connection string. They come in useful!
Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling. Please consider this example for demonstration only!
we will create a method data table in which we will take excel sheet info in data table or data set after that we will push that data into SQL database table using SQL bulk
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
for()
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(#"Data
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
SqlBulkCopy objbulk = new SqlBulkCopy(con);
objbulk.DestinationTableName = "customer1";
objbulk.ColumnMappings.Add("CustomerID", "CustomerID");
objbulk.ColumnMappings.Add("City", "City");
objbulk.ColumnMappings.Add("Country", "Country");
objbulk.ColumnMappings.Add("PostalCode", "PostalCode");
objbulk.WriteToServer(dt);
}
}
catch (Exception ex)
{
Response.Write(ex);
}
}
protected DataTable DataExcel()
{
DataTable dt = new System.Data.DataTable();
try
{
string filenname=#"C:\Users\sani singh\Documents\Excel03.xls";
string sWorkbook = "[Sheet1$]";
string ExcelConnectionString=#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString);
OleDbConn.Open();
OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook),
OleDbConn);
DataSet ds = new DataSet();
OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd);
sda.Fill(ds);
dt = ds.Tables[0];
OleDbConn.Close();
}
catch(Exception ex)
{
Response.Write(ex);
}
return dt;
}
}
}
Add a DataTable which can hold the Excel data generated via OLEDb.
string excelconnectionstring = String.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;");
using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring))
{
using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
{
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
dtBulkUpload.Load(dr);
}
}
Then serialize this DataTable to XML which can be sent to SQL Stored Proc. This approach is very useful if there are too many fields and you can send all in a single parameter
using (StringWriter strXML = new StringWriter())
{
dtBulkUpload.TableName = "BulkUpload";
dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false);
xmlString = strXML.ToString();
}
using (SqlCommand cmd = new SqlCommand("Stored PROC Name"))
{
cmd.Parameters.AddWithValue("#dtBulkUpload", bulkUploadData);
//SqlParameter returnParameter = cmd.Parameters.Add("#result", SqlDbType.NVarChar);
//returnParameter.Direction = ParameterDirection.Output;
cmd.Parameters.Add("#result", SqlDbType.NVarChar,3000);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
query = (string)(cmd.Parameters["#result"].Value.ToString());
con.Close();
How can I save a DataTable to a file. accdb (Access) existing one? I've used the following code and it does not work:
using (OleDbConnection oledbConnection = new OleDbConnection(connection))
{
oledbConnection.Open();
string query = "SELECT * FROM Student";
using (OleDbCommand oledbCommand = new OleDbCommand(query, oledbConnection))
{
using (OleDbDataAdapter oledbDataAdapter = new OleDbDataAdapter(oledbCommand))
{
using (OleDbCommandBuilder oledbCommandBuilder = new OleDbCommandBuilder(oledbDataAdapter))
{
oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand(true);
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand(true);
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand(true);
oledbDataAdapter.Update(dataTable);
}
}
}
oledbConnection.Close();
}
The variable dataTable is initialized with the original contents of the file, then it was modified by adding a row and now I have to update the table in the database.
I tried using the following code, but that does not work :(
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM Student", connection);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(da);
da.InsertCommand = cmdBuilder.GetInsertCommand(true);
// create and insert row in the DataTable
da.Update(dataTable);
Assuming that you have made some changes in the datatable, then you could pass the generated update/insert/delete command to the adapter in this way
oledbDataAdapter.DeleteCommand = oledbCommandBuilder.GetDeleteCommand();
oledbDataAdapter.InsertCommand = oledbCommandBuilder.GetInsertCommand();
oledbDataAdapter.UpdateCommand = oledbCommandBuilder.GetUpdateCommand();
oledbDataAdapter.Update(datatable);
Now the adapter knows how to update your table
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
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);
}