Chevy Mark Sunderland

Chevy Mark Sunderland

  • NA
  • 188
  • 167.3k

Inserting data into MySQL with ASP.NET + C#

Nov 9 2012 3:19 AM

Hello there, I need your help.

I have error and problem when tried insert into mysql table data of gridview.

If tried th same query in mysql workbench I don't have problem, instead the aspx page print this error, why?

The problem occurs when I want to run multiple inserts in mysql table.

Thank you in advance, I hope your help.

ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO tbl_g (q) VALUES (2)' at line 1

The code behind

protected void btnInsert_Click(object sender, EventArgs e)
{
System.Text.StringBuilder strSql = new System.Text.StringBuilder(string.Empty);
OdbcCommand cmd = new OdbcCommand();

for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chkUpdate = (CheckBox)
GridView1.Rows[i].Cells[0].FindControl("chkSelect");
if (chkUpdate != null)
{
if (chkUpdate.Checked)
{
strID = GridView1.Rows[i].Cells[1].Text;
strName = ((TextBox)

GridView1.Rows[i].FindControl("p")).Text;
string strQuery = "INSERT INTO tbl_g (q) VALUES (" + strName + ");";

Response.Write(strQuery);
strSql.Append(strQuery);
}
}
}
try
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strSql.ToString();
cmd.Connection = myConnectionString;
myConnectionString.Open();
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string errorMsg = "Error";
errorMsg += ex.Message;
throw new Exception(errorMsg);
}
finally
{
myConnectionString.Close();
}
UncheckAll();

}

Answers (1)