inserting data from excel to sql table - c#

Am getting an error while inserting data from excel to the database table.
this is the error Incorrect syntax near 'NAME'
this is my code:
protected void btninsert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
conStr = ConfigurationManager.ConnectionStrings["SqlConString"].ConnectionString;
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("insert into MedicalItems (ITEM NAME,GROUP,ITEM TYPE,COST PRICE,SELLING PRICE,PURCHASE UOM,PURCHASE PACKAGING,DISPENSING UOM,QTY ON HAND,EXPIRY DATE,REORDER LEVEL,REORDER QUANTITY,BATCH#) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "','" + g1.Cells[4].Text + "','" + g1.Cells[5].Text + "','" + g1.Cells[6].Text + "','" + g1.Cells[7].Text + "','" + g1.Cells[8].Text + "','" + g1.Cells[9].Text + "','" + g1.Cells[10].Text + "','" + g1.Cells[11].Text + "','" + g1.Cells[12].Text + "','" + g1.Cells[13].Text + "')", con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
Label2.Text = "Records inserted successfully";
}

Wrap the column names within [] like [ITEM NAME], for all the columns with whitespaces.

Related

Select DataGrid Index based on row ID value?

This is my first project, so be gentle
I know how to get the current row Index value and its [ID] value using the following code:
public void Sql_Address_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid gd = (DataGrid)sender;
if (gd.SelectedItem is DataRowView row_selected)
{
Public_Strings.selectedID = Int32.Parse(row_selected["ID"].ToString());
Public_Strings.currentIndex = Int32.Parse(sql_address.SelectedIndex.ToString());
}
}
I am displaying synchronized SQL table values in two different places - a DataGrid in TabItem 1 and a couple of editable TextBoxes in TabItem 2. I also have Next/Previous buttons in TabItem 2 to move up and down the DataGrid Index that also refresh the content of the TextBoxes. Everything works fine, but when I add or modify an entry in the SQL table, the Index shifts, because of the grouping and the Next/Previous buttons reset to the default Index 0.
I know how to bypass this when Deleting an entry by using this method:
public void Delete(object sender, RoutedEventArgs e)
{
MessageBoxResult messageBoxResault = System.Windows.MessageBox.Show("Ali se prepričani?", "Potrditev izbrisa", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResault == MessageBoxResult.Yes)
{
Public_Strings.currentIndex= sql_address.SelectedIndex-1;
SqlCommand cmd = new SqlCommand
{
CommandText = "DELETE FROM cbu_naslovi WHERE [ID]='" + Public_Strings.selectedID + "'",
Connection = con
};
cmd.ExecuteNonQuery();
Datagrid();
sql_address.SelectedIndex = Public_Strings.currentIndex;
}
}
My Add method:
public void Add(object sender, RoutedEventArgs e)
{
MessageBoxResult messageBoxResault = System.Windows.MessageBox.Show("Ali se prepričani?", "Potrditev vnosa", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResault == MessageBoxResult.Yes)
{
SqlCommand cmd = new SqlCommand
{
CommandText = "INSERT INTO cbu_naslovi VALUES ('" + ulica.Text + "','" + hisna_st.Text + "','" + id_hise.Text + "','" + postna_st.Text + "','" + obmocje.Text + "','" + katastrska_obcina.Text + "','" + st_objekta.Text + "','" + st_delov.Text + "','" + st_parcele_1.Text + "','" + st_parcele_2.Text + "','" + st_parcele_3.Text + "','" + st_parcele_4.Text + "','" + st_parcele_5.Text + "','" + st_parcele_6.Text + "','" + st_parcele_7.Text + "')",
Connection = con
};
cmd.ExecuteNonQuery();
Datagrid();
address.Content = ulica.Text.ToString() + " " + hisna_st.Text.ToString() + id_hise.Text.ToString();
}
}
I need a solution that allows me to select the index based on the ID value of row, so that when I add or modify and entry in the SQL table the Next/Previous buttons continue from the newly added/modified index. Basically something in the lines of:
sql_address.SelectedIndex = "sql_address.SelectedIndex where sql_address[ID] = Public_Strings.currentIndex" - Paraphrasing
Visual refference:
https://image.ibb.co/k2XDAz/1.png
https://image.ibb.co/gJ00qz/2.png
I solved this issue using the following combination of code:
public void Add(object sender, RoutedEventArgs e)
{
MessageBoxResult messageBoxResault = System.Windows.MessageBox.Show("Ali se prepričani?", "Potrditev vnosa", System.Windows.MessageBoxButton.YesNo);
if (messageBoxResault == MessageBoxResult.Yes)
{
SqlCommand cmd = new SqlCommand
{
CommandText = "INSERT INTO cbu_naslovi VALUES ('" + ulica.Text + "','" + hisna_st.Text + "','" + id_hise.Text + "','" + postna_st.Text + "','" + obmocje.Text + "','" + katastrska_obcina.Text + "','" + st_objekta.Text + "','" + st_delov.Text + "','" + st_parcele_1.Text + "','" + st_parcele_2.Text + "','" + st_parcele_3.Text + "','" + st_parcele_4.Text + "','" + st_parcele_5.Text + "','" + st_parcele_6.Text + "','" + st_parcele_7.Text + "')",
Connection = con
};
cmd.ExecuteNonQuery();
SaveID();
sql_address.SelectedIndex = 0;
SearchIndex();
address.Content = ulica.Text.ToString() + " " + hisna_st.Text.ToString() + id_hise.Text.ToString();
search.Text = string.Empty;
}
}
public void SaveID()
{
DatagridIndex();
sql_address.SelectedIndex = sql_address.Items.Count - 1;
Public_Strings.saveID3 = Public_Strings.saveID1;
Datagrid();
}
public void SearchIndex()
{
if (Public_Strings.saveID3 == Public_Strings.saveID1) { }
else
{
sql_address.SelectedIndex++;
SearchIndex();
}
}
public void DatagridIndex()
{
SqlCommand cmd = new SqlCommand
{
CommandText = "SELECT * FROM [cbu_naslovi] ORDER BY [ID] ASC",
Connection = con
};
SqlDataAdapter da = new SqlDataAdapter(cmd);
dataGrid1 = new DataTable("cbu_naslovi");
da.Fill(dataGrid1);
sql_address.ItemsSource = dataGrid1.DefaultView;
}
public void Datagrid()
{
SqlCommand cmd = new SqlCommand
{
CommandText = "SELECT * FROM [cbu_naslovi] ORDER BY [ULICA] ASC, LEN ([HS]) ASC, [HS] ASC, [HID] ASC",
Connection = con
};
SqlDataAdapter da = new SqlDataAdapter(cmd);
dataGrid1 = new DataTable("cbu_naslovi");
da.Fill(dataGrid1);
sql_address.ItemsSource = dataGrid1.DefaultView;
}
TLDR version, add an entry and create a "new" Datagrid ordered by ID ASC, the last ID on the list is always going to be the newly created one as long as you are using auto-increment. Save that ID in a NEW string. Now call for the "correct" Datagrid, order it the way you want and compare the IDs starting from Index 0 with the saved one until you find the right one, then stop the code. Your add button should now redirect you to the correct index and your next/previous buttons should work fine.
Edit_v1:
There might be an easier solution, but I'm too stupid to find it (could theoretically solve it with a method that adds +1 to a counter every time you press the Add button, but be careful that you start with the correct number of IDs when importing CVS file).
Edit_v2: Or just SQL to find the last ID:
Safest way to get last record ID from a table
Then use the following method to convert it to string:
How can I get SQL result into a STRING variable?
Edit_v3: Another method:
public void Add(object sender, RoutedEventArgs e)
{
if (ulica.Text != "" && hisna_st.Text != "" && postna_st.Text != "" && obmocje.Text != "")
{
MessageBoxResult messageBoxResault = MessageBoxEx.Show(this, "Ali se prepričani?", "Potrditev vnosa", MessageBoxButton.YesNo);
if (messageBoxResault == MessageBoxResult.Yes)
{
SqlCommand cmd = new SqlCommand
{
CommandText = "INSERT INTO cbu_naslovi VALUES ('" + ulica.Text + " " + hisna_st.Text + id_hise.Text + "','" + ulica.Text + "','" + hisna_st.Text + "','" + id_hise.Text + "','" + postna_st.Text + "','" + obmocje.Text + "','" + katastrska_obcina.Text + "','" + st_objekta.Text + "','" + st_delov.Text + "','" + st_parcele_1.Text + "','" + st_parcele_2.Text + "','" + st_parcele_3.Text + "','" + st_parcele_4.Text + "','" + st_parcele_5.Text + "','" + st_parcele_6.Text + "','" + st_parcele_7.Text + "','" + st_parcele_8.Text + "','" + st_parcele_9.Text + "','" + st_parcele_10.Text + "','" + st_parcele_11.Text + "','" + st_parcele_12.Text + "','" + st_parcele_13.Text + "','" + st_parcele_14.Text + "','" + st_parcele_15.Text + "','" + st_parcele_16.Text + "','" + st_parcele_17.Text + "'); SELECT SCOPE_IDENTITY();",
Connection = con
};
int lastId = Convert.ToInt32(cmd.ExecuteScalar());
InvokeDataGridAddress();
SetToRow(lastId);
address.Content = ulica.Text.ToString() + " " + hisna_st.Text.ToString() + id_hise.Text.ToString();
}
}
else
{
MessageBoxEx.Show(this, "Vpisati je potrebno podatke!");
}
}
public int CurrentID
{
get
{
int tmp = 0;
if (dg_address.SelectedIndex >= 0)
{
int.TryParse(dtAddress.Rows[dg_address.SelectedIndex].ItemArray[0].ToString(), out tmp);
}
return tmp;
}
}
public void SetToRow(int Id)
{
Mouse.OverrideCursor = System.Windows.Input.Cursors.Wait;
dg_address.SelectionChanged -= DG_Address_SelectionChanged;
while (CurrentID != Id && dg_address.SelectedIndex < dtAddress.Rows.Count - 1)
{
dg_address.SelectedIndex++;
}
dg_address.SelectionChanged += DG_Address_SelectionChanged;
Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
}

Insert Query in C# with MS access Database

When I am inserting data in MS access database .it is not giving any error but data not inserted in database
code:
private void btnsubmit_Click(object sender, EventArgs e)
{
int row = dataGridView1.RowCount;
for (int i = 0; i < row - 1; i++)
{
String str = "insert into JDS_Data(job_no,order_no,Revision,DesignSpec,Engine_Type,date,LE_IN_Designer,CPH_Designer,Exp_Del_Week,Action_code,Rev_Description,Ref_pattern,Name_of_mock_up,EPC_Drawing,Turbocharger_no_Type,Engine_Specific_Requirement,Draft_sketch_with_details,Air_cooler_type,Description_of_Job,SF_No,Standard,Prority_Sequence,Remark,Part_family,Modified_Date,User) values('" + txtjobno.Text + "','" + txtorderno.Text + "','" + txtrevison.Text + "','" + txtds.Text + "','" + txtenginetype.Text + "','" + dateTimePicker1.Text + "','" + txtleindesigner.Text + "','" + txtcphdesigner.Text + "','" + txtexpweek.Text + "','" + txtactioncode.Text + "','" + txtrevdescription.Text + "','" + txtrefpatern.Text + "','" + txtmockup.Text + "','" + txtepcdwg.Text + "','" + txtturbono.Text + "','" + txtenginereq.Text + "','" + txtdraft.Text + "','" + txtaircolertype.Text + "','" + txtdespjob.Text + "','" + dataGridView1.Rows[i].Cells[0].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[1].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[2].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[3].Value.ToString() + "','" + dataGridView1.Rows[i].Cells[4].Value.ToString() + "','" + DateTime.Today + "','" + mdlconnection.user_name + "')";
int dd = mdlconnection.excuteQuery(str);
MessageBox.Show(str);
//if (dd > 0)
{
MessageBox.Show("Data Saved Successfully..!!!");
}
}
}
Code:
public static int excuteQuery(string q)
{
int d = 0;
try
{
OleDbCommand cmd = new OleDbCommand(q, con);
d = cmd.ExecuteNonQuery();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return d;
}
if you are using DataContext (you provided to little info)
you should rewrite your statement to match the example:
var customers = db.ExecuteQuery<Customer>(#"SELECT CustomerID, CompanyName, ContactName, ContactTitle,
Address, City, Region, PostalCode, Country, Phone, Fax
FROM dbo.Customers
WHERE City = {0}", "London");
I should suggest to use this tutorial for the connection instead actually

Adding data to database from frontend to backend

I'm getting this error code: "unclosed quotation mark after the character string" on the line: cmd.ExecuteNonQuery();
I've looked, but I don't know what's wrong. I also tried just putting two of the textboxe, but I can't seem to debug it. Please advise. Thanks!
Here's the code:
namespace Inventory
{
public partial class NewData : System.Web.UI.Page
{
SqlConnection cn = new SqlConnection("Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234");
protected void Page_Load(object sender, EventArgs e)
{
}//end page load
protected void addButton_Click(object sender, EventArgs e)
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" + Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
cmd.ExecuteNonQuery();
cn.Close();
status.Visible = true;
status.Text = "Added succesffully!";
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//end add button
protected void clearButton_Click1(object sender, EventArgs e)
{
Typetb.Text = "";
Maketb.Text = "";
Modeltb.Text = "";
Serialtb.Text = "";
Assignedtb.Text = "";
Locationtb.Text = "";
Notestb.Text = "";
}//clear button
}//end
}//end
As far as I can see, you have unnecessary single quote at the end of your query.
Notestb.Text + "')'
^^ here
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your connections and commands automatically instead of calling Close or Dispose methods manually.
using(var cn = new SqlConnection(conString))
using(var cmd = cn.CreateCommand())
{
// Set your CommandText property with your parameter definitions
// Add your parameters and their values with Add method
// Open your connection
// Execute your query.
}
Your command ends with an extra single quote. It should be:
cmd.CommandText = "INSERT INTO Inventory values('" +
Typetb.Text + " ',' " + Maketb.Text + "','" + Modeltb.Text +
"','" + Serialtb.Text + "','" + Assignedtb.Text + "','" +
Locationtb.Text + "','" + Notestb.Text + "')";
I think the problem is
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','" +
Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text + "')'";
there you single comma ' after the right bracket ).
Should have been:
cmd.CommandText = "INSERT INTO Inventory values('" + Typetb.Text + " ',' "
+ Maketb.Text + "','" + Modeltb.Text + "','" + Serialtb.Text + "','"
+ Assignedtb.Text + "','" + Locationtb.Text + "','" + Notestb.Text
+ "')";

Code Doesn't work. C# Execute Non Query

string conStr = null;
SqlCommand cmd;
SqlConnection cnn;
string sql = null;
conStr = "Data Source=DELL-PC\\SQLEXPRESS;Initial Catalog=DBMSI;Integrated Security=True";
sql = "insert into CEC_Employee values('"+empid + "','" + name + "','" + fname + "','" + mname + "','" + lname + "','" + address + "','" + postcode + "','" + job + "','" + sdate + "','" + whours + "','" + sph + "','" + spa + "','" + location + "','" + working + "','" + gender + "','" + dob + "','" + pn + "','" + exp + "','" + vtype + "','" + vexp + "','" + qualification + "','" + email + "','" + number + "','" + nin + "','" + sort + "','" + acc + "','" + bank + "','" + nname + "','" + rel + "','" + addkin + "','" + cnokin + "','" + emailkin + "')";
cnn = new SqlConnection(conStr);
try
{
cnn.Open();
cnn = new SqlConnection(conStr);
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Open();
MessageBox.Show("Employee Details registered Succesffuly");
// Keeps on moving to the Exception part of the code. Doesn't execute the try portion of the program.
}
catch (Exception ex)
{
MessageBox.Show("Error Occoured - Employee Details were not recorded");
}
Found the code online. Please help to make it work. Thanks!
Hopefully your primary key on CEC_Employee isn't "empid", and if it is set to be an autonumber, like IDENTITY(1,1), the SQL command will fail as it won't let you hand it a primary key value.
This is speculation of course, since you haven't posted the actual exception message or stack trace.

Data not inserting in c# but same data is inserted in SQL Server query browser

I have a link button in my gridview at which I have some to insert value in table but it is not inserting but query data on debug mode when I tested on SQL Server it is inserted so whats the problem
protected void gvPO_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
c.GetConection();
SqlCommand cmd = new SqlCommand("delete from tmpMateIN", c.con);
cmd.ExecuteNonQuery();
DataTable dt;
int index = Convert.ToInt32(e.CommandArgument);
gvPO.SelectedIndex = index;
if (Convert.ToInt16(gvPO.SelectedIndex) < 0)
{
lblMsg.Text = "Please Select Code !";
return;
}
dt = oAccount.GetPO((int)Session["CompCode"], 79, Convert.ToInt16(((LinkButton)gvPO.Rows[gvPO.SelectedIndex].Cells[0].FindControl("lnkCode")).Text.ToString()));
for (int i = 0; i < dt.Rows.Count; i++)
{
String s6 = "insert into tmpMateIN(compcode ,msttype ,mstcode,mstdate ,mstchno ,mstblno ,mstbldt ,mstcust ,itdsrno , itditem ,itdquan ,itdrema ,itemname ,acctname ,ItmSize , unitname ,itemsize ,chno , chdt ,godown, packsize ,itdRate , itdDisc , itdAmou , mstInvNo , mstOrdNo,mstInvDt ,mstOrdDt ,mstrema , mstexcDes , msttaxDes ,msttaxper , mstfrghtDes , mstfrghtper , mstdeliDes ,mstpayDes , mstvaliDes, mstqno, mstqdt , itdthickness , itdlength ,itdwidth ,itdweight, itdtowt , acctaddr , custemail , mstpayMode , mstdepa,itdrefq,itdorgq)values(" + (int)Session["CompCode"] + ",79,'" + dt.Rows[i]["mstcode"] + "','" + dt.Rows[i]["mstdate"] + "'," + dt.Rows[i]["mstchno"] + ",'" + dt.Rows[i]["mstchno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstptcode"] + "','" + (i + 1) + "','" + dt.Rows[i]["itditem"] + "','" + dt.Rows[i]["itdquan"] + "','" + dt.Rows[i]["itdrema"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["AcctName"] + "','" + dt.Rows[i]["itdnarr"] + "','" + dt.Rows[i]["UnitName"] + "' ,'" + dt.Rows[i]["itdunit"] + "','','" + dt.Rows[i]["mstdate"] + "','',''," + dt.Rows[i]["itdRate"] + "," + dt.Rows[i]["itdamou"] + " ," + dt.Rows[i]["itdAmou"] + ",'" + dt.Rows[i]["mstInvNo"] + "','" + dt.Rows[i]["mstindno"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstdate"] + "','" + dt.Rows[i]["mstrema"] + "','','','" + dt.Rows[i]["mstTaxPer"] + "','" + dt.Rows[i]["mstfrghtDes"] + "','" + dt.Rows[i]["mstfrghtper"] + "','" + dt.Rows[i]["mstdeliDes"] + "','" + dt.Rows[i]["mstpayDes"] + "','" + dt.Rows[i]["mstvaliDes"] + "','" + dt.Rows[i]["mstqno"] + "','" + dt.Rows[i]["mstpodate"] + "','" + dt.Rows[i]["itdthickness"] + "','" + dt.Rows[i]["itdsource"] + "','" + dt.Rows[i]["itddestin"] + "','" + dt.Rows[i]["itdweight"] + "','" + dt.Rows[i]["itdtowt"] + "','','" + dt.Rows[i]["acctaddr"] + "','" + dt.Rows[i]["mstpayMode"] + "','" + dt.Rows[i]["mstContactPerson"] + "','" + dt.Rows[i]["mstlotno"] + "','" + dt.Rows[i]["mstsection"] + "' )";
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.ExecuteNonQuery();
}
c.CloseConnection();
Response.Redirect("Poreport.aspx");
}
}
You can run the SQL Server Profiler to see if the call is made to SQL Server for insertion at the time of execution of your program.
Suggestion: Why don't you use stored procedure instead of having this inline query this way:
var dr = dt.Rows[i];
SqlCommand cmd1 = new SqlCommand(s6, c.con);
cmd1.CommandType = System.Data.CommandType.StoredProcedure;
cmd1.CommandText = "tmpMateIN_Insert";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();
ADDED:
OR if you really want to stick with an inline query then preferred approach is to use parameterized inline query as shown below:
String s6 = "insert into tmpMateIN(compcode, msttype, mstcode, mstdate, ..." +
"values(#compcode, #msttype, #mstcode, #mstdate, ...";
cmd1.Parameters.Add(new SqlParameter("#compcode", (int)Session["CompCode"]);
cmd1.Parameters.Add(new SqlParameter("#msttype", 79);
cmd1.Parameters.Add(new SqlParameter("#mstcode", dr["mstcode"]);
cmd1.Parameters.Add(new SqlParameter("#mstdate", dr["mstdate"]);
// ...
cmd1.ExecuteNonQuery();

Categories