I loaded an Excel file into SQL Server and it's working fine, but I want to attach current date while importing this file. That means each row will have the date data loaded in. So each time I load the file, new data should take the current date, and the old data still have the old date.
How can I do that ?
Code for importing the Excel file:
string ssqltable = comboBox1.GetItemText(comboBox1.SelectedItem);
string myexceldataquery = "select * from [" + ssqltable + "$]";
try
{
OleDbConnection oconn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + imagepath + ";Extended Properties='Excel 12.0 Xml; HDR=YES;IMEX=1;';");
string ssqlconnectionstring = "Data Source=.;Initial Catalog=Bioxcell;Integrated Security=true";
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oconn);
oconn.Open();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
DataTable dt = new DataTable();
dt.Load(oledbcmd.ExecuteReader());
bulkcopy.DestinationTableName = ssqltable;
for (int i = 0; i < dt.Columns.Count; i++)
{
bulkcopy.ColumnMappings.Add(i, i);
}
bulkcopy.WriteToServer(dt);
oconn.Close();
}
and this for inserting date but not working for me
if (ssqltable == "Overseas")
{
conn.Open();
SqlCommand sqlc = new SqlCommand("delete from Overseas where Bonus = 'Bonus'", conn);
sqlc.ExecuteScalar();
SqlCommand Update1 = new SqlCommand("Update Overseas set ID = 1 Where ProductCode = 9630", conn);
Update1.ExecuteNonQuery();
SqlCommand Update2 = new SqlCommand("Update Overseas set ID = 2 Where ProductCode = 9628", conn);
Update2.ExecuteNonQuery();
SqlCommand Update3 = new SqlCommand("Update Overseas set ID = 3 Where ProductCode = 9629", conn);
Update3.ExecuteNonQuery();
SqlCommand Update4 = new SqlCommand("Update Overseas set ID = 4 Where ProductCode = 9632", conn);
Update4.ExecuteNonQuery();
SqlCommand Update5 = new SqlCommand("Update Overseas set ID = 5 Where ProductCode = 9631", conn);
Update5.ExecuteNonQuery();
SqlCommand Update6 = new SqlCommand("insert into Overseas (Date) Values (GETDATE())", conn);
Update6.ExecuteNonQuery();
}
No error and only one date was inserted. How can I solve this problem ?
If you have control over the table, you can create a new date column with a default value of GETDATE():
ALTER TABLE <tablename>
ADD ROW_CREATE_TS DATETIME DEFAULT GETDATE()
Ref: https://learn.microsoft.com/en-us/sql/relational-databases/tables/specify-default-values-for-columns
Related
I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.
I´m starting to develop in C# and SQL Server, I don´t know how to extract information from one excel specific colum.
I have this code working, but what i need it´s to compare a textbox with a specific column and get the data:
Example
Select *
From T_Empleado
Where "Specific column" = "textbox".
public void mostrarExcel()
{
String name = "Sheet1";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + "C:\\Users\\alegriad\\Desktop\\sample\\Book2.xlsx" + "; Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]'", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
dgv_Reporte.DataSource = data;
}//mostrarExcel
Thank you.
You can write your query like this
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] where columnName = '"+ YourTextboxValue+ "'" , con);
I try with sample excel like below
And my query like this
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$] WHERE Name = 'T1'", con);
This works for me.
I have multiple queries like this right now which involve updating different fields of the same row in an Access database:
//Update database
string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=" + "database.accdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con);
var accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//update last10attemptssum
updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//increment totalquestionattempt
updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
con.Close();
I was wondering if there is a more efficient way of running these update queries - ie. combining them into one query.
There is no need to use an OleDbDataAdapter in your context above. You could use a simple command and execute it
Said that, an Update sql statement can update more than one field. Just write
string updatequery = #"UPDATE [table] SET [Last10Attempts] = ?,
[Last10AttemptsSum] = ?,
[total-question-attempts] = ?
WHERE id = ?";
using(OleDbConnection con = new OleDbConnection(.........))
using(OleDbCommand cmd = new OleDbCommand(updatequery, con))
{
con.Open();
cmd.Parameters.AddWithValue("Last10Attempts", last10attempts);
cmd.Parameters.AddWithValue("Last10AttemptsSum", counter);
cmd.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
cmd.Parameters.AddWithValue("ID", currentid + 1);
cmd.ExecuteNonQuery();
}
The only thing to keep present when working with OleDb is the fact that the parameters are used in the exact order in which the parameter placeholder appears in the command text. So they should be added to the parameter collection in the order expected by the command text
This is how i am import my Excel file:
stirng file = "c:\myFile.xlsx";
DataGridView dgvIM;
private void Import()
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
file +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dgvIM.DataSource = data;
}
What i want to do is import my Excel file but with specific condition, my second column contain several groups of strings ("First", "Second" etc..) and i want to add only the column with name "First" and not the whole list.
How can i do that ?
Just use a where condition on the sql command like this
string cmdText = "Select * From [" + name + "$] WHERE secondColumnName = 'First'";
using(OleDbConnection con = new OleDbConnection(constr))
using(OleDbCommand oconn = new OleDbCommand(cmdText con))
{
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
sda.Fill(data);
dgvIM.DataSource = data;
}
Note that in your connectionstring you specify HDR=YES, this means that the first non blank line of your excel sheet contains headers that are interpreted as column names. You should update your query setting the correct column name in the WHERE condition
EDIT In response at your comments below, if you want to retrieve every row where AGE is 12 the query becomes
string cmdText = "Select * From [" + name + "$] WHERE Age = 12";
I do have a ListView which i call from Database ( its selection of data ) in each row i have one Remove, Update Button.
i Bind each button to the ID in listview so when i click it have to return that row value only!
BUT i want to call this value in my query Function to update or Remove the selected Row.
I'm not sure how to call this value into Query.
here is my binding sample:
<Button Name="delete" Click="Delete_Click" CommandParameter="{Binding Path=empID}">
Here is how i call it :
Button _button = (Button)sender;
string empID = _button.CommandParameter.ToString();
\sql stuff
SqlCeConnection con = new SqlCeConnection();
SqlCeDataAdapter ad = new SqlCeDataAdapter();
SqlCeCommand cmd = new SqlCeCommand(empID);
String str = "UPDATE employee SET Isdeleted ='1' WHERE empID= " + empID;
cmd.Parameters.AddWithValue("#empID", empID);
ad.SelectCommand = cmd;
Hope i can get some help as this Query will never worked so far!
Not sure if it will work but u should give it a try, I made it for a local sdf database
var con = new SqlCeConnection("Data Source=" + "|DataDirectory|\\Database1.sdf");
String str = "UPDATE employee SET Isdeleted ='1' WHERE empID= '"+ empID +"'";
var cmd = new SqlCeCommand(str,con);
try
{
con.Open();
}
catch (Exception a)
{
Console.WriteLine(a.ToString());
}
finally
{
cmd.ExecuteNonQuery();
con.Close();
}
SqlCeConnection con = new SqlCeConnection();
SqlCeDataAdapter ad = new SqlCeDataAdapter();
SqlCeCommand cmd = new SqlCeCommand(empID);
String str = "UPDATE employee SET Isdeleted ='1' WHERE empID= " + empID;
cmd.Parameters.AddWithValue("#empID", empID);
ad.SelectCommand = cmd;
this is a strange setup
perhaps:
SqlCeConnection con = new SqlCeConnection();
SqlCeDataAdapter ad = new SqlCeDataAdapter();
String str = "UPDATE employee SET Isdeleted ='1' WHERE empID= #empID";
SqlCeCommand cmd = new SqlCeCommand(str);
cmd.Parameters.AddWithValue("#empID", empID);
ad.UpdateCommand = cmd;