无法将数据插入数据库

时间:2016-01-07 04:59:20

标签: c# asp.net sql-server

我似乎无法将数据插入我的数据库。我想知道我是否正确使用了SCOPE_IIDENTITY。我只想将这些数据插入到我的数据库中,而无需手动键入PurchOrderId。

在我的BllPurchaseOrder.cs文件中:

public int InsertPO(String PurchName, String PurchDesc, int SuppId)
    {

        StringBuilder sql;
        SqlCommand sqlCmd;
        int result;

        result = 0;

        sql = new StringBuilder();
        sql.AppendLine("INSERT INTO PurchaseOrder(PurchName, PurchDesc, SuppId, CreateDate, SentStatus)");
        sql.AppendLine(" ");
        sql.AppendLine("VALUES (@PurchName, @PurchDesc, @SuppId, @CreateDate, @SentStatus)");
        sql.AppendLine(" ");
        sql.AppendLine("SELECT CAST(scope_identity() AS int)");
        sql.AppendLine(" ");
        SqlConnection conn = dbConn.GetConnection();
        try
        {
            sqlCmd = new SqlCommand(sql.ToString(), conn);

            sqlCmd.Parameters.AddWithValue("@PurchName", PurchName);
            sqlCmd.Parameters.AddWithValue("@PurchDesc", PurchDesc);
            sqlCmd.Parameters.AddWithValue("@CreateDate", DateTime.Now);
            sqlCmd.Parameters.AddWithValue("@SuppId", SuppId);
            sqlCmd.Parameters.AddWithValue("@SentStatus", "Sent");

            result = sqlCmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            errMsg = ex.Message;
        }
        finally
        {
            conn.Close();
        }

        return result;
    }

在我的InsertPO.aspx.cs中:

int result = 0;

        string PurchName = tbPurchName.Text;
        string PurchDesc = tbPurchDesc.Text;
        int SuppName = int.Parse(ddlSuppName.SelectedValue);

        BllPurchaseOrder po = new BllPurchaseOrder();
        result = po.InsertPO(PurchName, PurchDesc, SuppName);

        if (result > 0)
        {
            Response.Write("<script>alert('Insert Successful!'); </script>");
            Response.Redirect("~/ViewAllPO.aspx");
        }
        else
        {
            Response.Write("<script>alert('Insert NOT Successful'); </script>");
        }

2 个答案:

答案 0 :(得分:1)

使用ExecuteScalar而不是ExecuteNonQuery,因为您选择了要返回的值。

答案 1 :(得分:0)

看起来您的代码很好并且可以正常工作,

但问题是你忘了打开连接。

所以请打开连接。

问候。