无法插入到我的数据库表中

本文关键字:数据库 我的 插入 | 更新日期: 2023-09-27 18:19:49

我正在尝试将文本框值插入数据库。但我被提示了一个错误"关键字'table'附近的语法不正确"cmd.ExecuteNonQuery();"有错误。我的代码出了什么问题?

以下是我的代码:

string query;
string str = "Data Source=blank blank blank;Initial Catalog=test;User ID=hello;Password=password";
SqlConnection con = new SqlConnection(str);
con.Open();
query = "INSERT INTO table dbo.url_map Values ('" + tbLongURL.Text + "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();

无法插入到我的数据库表中

正确的语法是

query = "INSERT INTO dbo.url_map Values ('" + tbLongURL.Text + "')";

基本上,您在查询中添加了单词"table",这不是SQL语法。它是

INSERT INTO tablename

您没有对文本进行转义,这不仅会破坏SQL查询,而且如果输入未被清除,则会使您容易受到SQL注入的攻击。你应该做什么:

string query;
string str = "Data Source=blank blank blank;Initial Catalog=test;User ID=hello;Password=password";
SqlConnection con = new SqlConnection(str);
con.Open();
query = "INSERT INTO dbo.url_map Values (@Url)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Url", tbLongURL.Text);
cmd.ExecuteNonQuery();
con.Close(); 

dbo.url_map表中是否只有一列?如果该表还有其他列,可以尝试该查询

INSERT INTO dbo.url_map(login) VALUES('" + tbLogonURL.Text + "')";

因为当您没有指定要插入的列日期时,您的DB将尝试为表的所有列取日期,如果您有列id,登录并通过,它将无法为id和通过取日期,这可能会导致插入错误。