插入值没有到达服务器

本文关键字:服务器 插入 | 更新日期: 2023-09-27 18:09:05

我使用ASP.NET 4.0, C #, SQL Server 2008 R2

我收到错误

"Cannot insert the value NULL into the column 'columnID', table 'table name'; column does not allow nulls. INSERT fails.  The statement has been terminated."

我有一个查询,获取最后一个ID值并将其放入textbox,然后我使用textbox.text值将ID插入表中,参见下面的代码。

    string ID_Sel = "SELECT TOP 1 columnID FROM table ORDER BY columnID DESC";
    string ID_Ins = "INSERT INTO table (columnID) VALUES (@id)";
    SqlConnection con = new SqlConnection(connection string);
    SqlCommand cmdsel = new SqlCommand(ID_Sel, con);
    SqlCommand cmdins = new SqlCommand(ID_Ins, con);
    con.Open();
    SqlDataReader read = cmdsel.ExecuteReader();
    read.Read();
    string a = read["columnID"].ToString();
    for (int i = 0; i < 1; i++)
    {
        string val1 = a.Substring(1, a.Length - 1);
        int b = Convert.ToInt32(val1) + 1;
        string val2 = a.Substring(0, a.Length - 6);
        a = val2 + b.ToSting("000000");
    }
    TextBox.Text = a;
    con.Close();
    TextBox.Attributes.Add("readonly", "readonly");
    try
    {
        con.Open();
        cmdins.Parameter.AddWithValue("@id", TextBox.Text);
        cmdins.ExecuteNonQuery();
        con.Close();
    }
    catch(Exception ex)
    {
        error.Text = ex.Message;
    }

我的Textbox显示记录的下一个ID,但我的错误textbox显示:

"Cannot insert the value NULL into the column 'columnID', table 'table name'; column does not allow nulls. INSERT fails.  The statement has been terminated."

我的问题是为什么我的textbox显示下一个记录的正确ID,但我发送null到数据库?

插入值没有到达服务器

ID列是否为整型?如果是,不妨试试:

cmdins.Parameter.Add("@id", SqlDbType.Int);
cmdins.Parameter["@id"].Value = Int.Parse(TextBox.Text);

你的代码张贴不编译,但这里有一个简化的版本,应该接近:

string ID_Sel = "SELECT TOP 1 columnID FROM table ORDER BY columnID";
string ID_Ins = "INSERT INTO table (columnID) VALUES (@id)";
SqlConnection con = new SqlConnection(connection string);
SqlCommand cmdsel = new SqlCommand(ID_Sel, con);
SqlCommand cmdins = new SqlCommand(ID_Ins, con);
con.Open();
var a = cmdsel.ExecuteScalar();  // use ExecuteScalar to get the only value
int b = Convert.ToInt32(a) + 1;
textBox.Text = b;
con.Close();
textBox.Attributes.Add("readonly", "readonly");
try
{
    con.Open();
    cmdins.Parameters.AddWithValue("@id", b);   //  use the variable instead of the TextBox property.
    cmdins.ExecuteNonQuery();
    con.Close();
}
catch(Exception ex)
{
error.Text = ex.Message;
}