-1

How to fix the SQL query that come out like this

insert into T (NO_ID, Room, RoomID, Name,)
values (10, 10, 10, 10,)

The button 3 when click will save the data to SQL

private void button3_Click(object sender, EventArgs e)
{
    string[] text = new string[DT.Columns.Count];

    foreach (DataColumn DC in DT.Columns)
    {
        for (int k = 0; k < DT.Columns.Count; k++)
        {
            // to save the datacolumn headertext name to string[]
            text[k] = DC.Table.Columns[k].ToString();
        }
    }
}

The SQL parts t11 is SQL connection string

SqlConnection SC = new SqlConnection(T11);
SC.Open();

// SQL query parts
StringBuilder command = new StringBuilder("insert into ");
//T33 is the table name
command.Append(T33).Append("(");

// I use the forloop to keep add string on `string[]`
for (int i = 0; i < DT.Columns.Count; i++)
{
    command.Append(text[i]+",");
}

command.Append(")values(");

for (int l= 0; l < DT.Columns.Count; l++)
{
    command.Append("10"+",");
}
command.Append(")");

using (SqlCommand sqlCommand = new SqlCommand(command.ToString(), SC))
{
    sqlCommand.ExecuteNonQuery();
}

The error screenshot:

enter image description here

3

1 Answer 1

2

You are generating your inputs in a loop by adding the value and a comma. This then means that you end up with 1 comma too many like this;

values(10,10,10,10,

So after you have generated your inputs you need to remove this. You can do this be reducing the length of the Stringbuilder, like this;

for (int i = 0; i < DT.Columns.Count; i++)
{
    command.Append(text[i]+",");
}

//Reduce the length of StringBuilder by 1
sb.Length--;
command.Append(")values(");

for (int l= 0; l < DT.Columns.Count; l++)
{
    command.Append("10"+",");
}

//Reduce the length of StringBuilder by 1
sb.Length--;
command.Append(")");

BTW: You need to switch to using AddParameter for your values, it is safer against SQL injection.

Sign up to request clarification or add additional context in comments.

1 Comment

i not very familiar with sqlparameter. but thank you for your remind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.