在c#中使用sqlParameters插入sqlserver

本文关键字:sqlParameters 插入 sqlserver | 更新日期: 2023-09-27 18:12:01

void BtnConfirmClick(object sender, EventArgs e)
{
   string first = txtFname.Text;
   string last  = txtLname.Text;

   string query = "INSERT INTO customer (first, last)";
          query += " VALUES (@fstName,@lstName)";
   string url = "Server=localhost;Database=flight;uid=root;password=1234";
   con1 = new MySqlConnection(url);
   con1.Open();
   cmd1 = new MySqlCommand(query,con1);
   //SqlParameter myParam = new SqlParameter("@fstName", SqlDbType.VarChar, 55);
   //myParam.Value = last;
   //SqlParameter myParam2 = new SqlParameter("@lstName", SqlDbType.VarChar, 55);
   //myParam2.Value = first;
   cmd1.Parameters.AddWithValue("@fstName", first);
   cmd1.Parameters.AddWithValue("@lstName", last);
   //cmd1.Parameters.Add(myParam);
   //cmd1.Parameters.Add(myParam2);
   cmd1.ExecuteNonQuery();
   con1.Close();
}

我不能插入数据到sqlServer,它一直得到一个错误。请帮助! !

在c#中使用sqlParameters插入sqlserver

乍一看你忘记了结束char (;在SQL查询中)。你需要:

string query = "INSERT INTO customer (first, last)";
       query += " VALUES (@fstName,@lstName);";