由于我的数据库表的列名是"from",得到错误

本文关键字:quot from 错误 于我的 我的 数据库 | 更新日期: 2023-09-27 18:18:29

我的数据库列名是"从",但我得到错误,而我改变列名到其他名称错误没有发生。为什么?

    protected void Button1_Click(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    con.Open();
    string qry="insert into Mynew(name,age,from,address,job)values(@name,@age,@from,@address,@job)";
    SqlCommand cmd= new SqlCommand(qry, con);
    cmd.Parameters.AddWithValue("@name", TextBox1.Text);
    cmd.Parameters.AddWithValue("@age", TextBox2.Text);
    cmd.Parameters.AddWithValue("@from",TextBox3.Text);
    cmd.Parameters.AddWithValue("@address", TextBox4.Text);
    cmd.Parameters.AddWithValue("@job", TextBox5.Text);
    cmd.ExecuteNonQuery();
    con.Close();
    }

当我改变列名城市没有得到错误,为什么会发生?

由于我的数据库表的列名是"from",得到错误

from是SQL中的保留关键字。如果您想将其用作表名,则必须使用:

转义
  • 把它放在反引号之间(MySQL和其他)
  • 将其放在方括号中(MS Access, SQL server)

insert into Mynew(name,age,`from`,address,job)values(@name,@age,@from,@address,@job)

insert into Mynew(name,age,[from],address,job)values(@name,@age,@from,@address,@job)

取决于你正在使用的数据库。

为避免混淆,显然最好使用不同的列名