Click here to Skip to main content
15,902,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi
I am first time trying to insert datatable value to database and getting error us insert statement wrong pls correct

Thanks

string connectionString = ConfigurationManager.ConnectionStrings["InvoiceConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connectionString);
StringBuilder sb = new StringBuilder(string.Empty);
string[] splitItems = null;
foreach (string item in sc)
{
    const string insertsql = "INSERT INTO Items(Description,ItemNo,Qty)VALUES";
    if (item.Contains(","))
    {
        splitItems = item.Split(",".ToCharArray());
        sb.AppendFormat("'{0}','{1}','{2}');",insertsql, splitItems[0], splitItems[1], splitItems[2]);



    }
}
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sb.ToString(),conn);
cmd.CommandType =CommandType.Text;
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterClientScriptBlock(typeof(Page),"script","alert('Record Successfuly saved');",true);
}
catch(System.Data.SqlClient.SqlException ex)
{
string msg = "AddItem Error:";
    msg += ex.Message;
    throw new Exception(msg);


}
finally
{
    conn.Close();

}



the error is

C#
System.Exception was unhandled by user code
  Message="AddItem Error:Incorrect syntax near 'INSERT INTO Items(Description,ItemNo,Qty)VALUES'."
  Source="App_Web_mi2y70b-"
  StackTrace:
       at Admin_Pages_DO_Management_EditDo.addItem(StringCollection sc) in c:\Inetpub\wwwroot\Invoice\Admin_Pages\DO_Management\EditDo.aspx.cs:line 240
       at Admin_Pages_DO_Management_EditDo.Submitbtn_Click(Object sender, EventArgs e) in c:\Inetpub\wwwroot\Invoice\Admin_Pages\DO_Management\EditDo.aspx.cs:line 278
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:
Posted
Updated 14-Nov-11 2:18am
v2
Comments
thatraja 14-Nov-11 5:12am    
what's the error message? include that in your question.

Debug your code and check what is the Insert statement gets formed in sb at run-time.

Have a look at below link for "SQL Insert" syntax.

http://www.w3schools.com/sql/sql_insert.asp
 
Share this answer
 
Prevent SQL injection by using parametrized queries
Using Parameterized queries to prevent SQL Injection Attacks in SQL Server[^]

Also careful with SQL Server Reserved Keywords[^], Use Square brackets[] for the field names & table names.

And your code is wrong, try this.

C#
const string insertsql = "INSERT INTO Items(Description,ItemNo,Qty)VALUES";
sb.AppendFormat("{0}",insertsql);  
foreach (string item in sc)
        {
            if (item.Contains(","))
            {
                splitItems = item.Split(",".ToCharArray());
                sb.AppendFormat("'{0}','{1}','{2}');",splitItems[0], splitItems[1], splitItems[2]);                    
            }
        }

But use parametrized queries
 
Share this answer
 
v2
Comments
Lancy.net 14-Nov-11 7:53am    
Hi thanks for your kind reply, i have tried your code also again i am getting the error as "AddItem Error:Incorrect syntax near 'INSERT INTO Items(Description,ItemNo,Qty)VALUES'." i will attach stack track also
thatraja 14-Nov-11 7:59am    
Can you get the value for the string-builder(sb) at debugging?
Lancy.net 14-Nov-11 9:57am    
yes , i made few changes pls see below

const string insertsql = "INSERT INTO Items(Description,ItemNo,Qty)VALUES (";
sb.AppendFormat("{0}", insertsql);
foreach (string item in sc)
{
if (item.Contains(","))
{
splitItems = item.Split(",".ToCharArray());
sb.AppendFormat("'{0}','{1}','{2}');", splitItems[0], splitItems[1], splitItems[2]);


}
}

Now if i have one row of data i am able to save it to database.
if more than one row getting error as incorrect statement near '{2}' pls chk
the error description says, you are executing an incomplete query.. i.e.
INSERT INTO Items(Description,ItemNo,Qty)VALUES

the right query should be

INSERT INTO Items(Description,ItemNo,Qty)VALUES('desc1','item1','qty1');

why your query's value part is blank... ??? and there are no brackets too!!!

check your loopings and, add check conditions where required... there should be no blank queries :) :)

debug it, and get the command string before it executes.. try to execute it inside the sql before the programe executes it..

hope you notice your mistake soon :)
 
Share this answer
 
Comments
Lancy.net 14-Nov-11 8:47am    
Hi just i have started learning asp.net.. i hope you are well experienced.. thanks for your comments..one request pls read the question before answering..it is adding data table value to sql..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900