如何通过存储过程将数据插入到sql数据表中

时间:2014-04-19 05:11:32

标签: c# asp.net sql-server stored-procedures ado.net

我想将asp.net中的数据集中的数据插入到SQL Server表中。

但是我无法将数据集中的值传递给我的存储过程plz帮助我

这是我的代码

private static SqlCommand WriteDatabase(SqlConnection conn)
{
            SqlCommand cmd = new SqlCommand(SP_insertData);
            cmd.Parameters.Clear();
            cmd.CommandType = CommandType.StoredProcedure;
            SqlParameterCollection pc = cmd.Parameters;

            pc.Add(CreateParameter("abID", System.Data.SqlDbType.Int));
            pc.Add(CreateParameter("fHitType", System.Data.SqlDbType.Int));
            pc.Add(CreateParameter("DateOfHit", System.Data.SqlDbType.DateTime));
            pc.Add(CreateParameter("TimeOfHit", System.Data.SqlDbType.Int));
            pc.Add(CreateParameter("fEmpid", System.Data.SqlDbType.Int));

            cmd.ExecuteNonQuery();

            return cmd;
}

private static SqlParameter CreateParameter(string p, SqlDbType sqlDbType)
{
        SqlParameter parameter = new SqlParameter("@" + p, sqlDbType);
        parameter.SourceColumn = p;
        return parameter;
}

我无法将数据集中的值传递给我的存储过程

2 个答案:

答案 0 :(得分:0)

您是否尝试过此代码:

SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString);

  public Boolean InserData(string abID, string fHitType,string DateOfHit, string TimeOfHit,string fEmpid)
{
    // SqlConnection oConnection = new SqlConnection("Connection_String");
    SqlCommand oCommand = new SqlCommand();
    oCommand.Connection = oConnection;
    oCommand.CommandText = "SP_insertData";
    oCommand.CommandType = CommandType.StoredProcedure;
    oCommand.Parameters.AddWithValue("@abID", abID);
    oCommand.Parameters.AddWithValue("@fHitType", fHitType);
    oCommand.Parameters.AddWithValue("@DateOfHit", DateOfHit);
    oCommand.Parameters.AddWithValue("@TimeOfHit", TimeOfHit);
    oCommand.Parameters.AddWithValue("@fEmpid", fEmpid);
    oConnection.Open();
    Boolean Result = Convert.ToBoolean(oCommand.ExecuteNonQuery());
    oConnection.Close();
    return Result;
}

它将返回true或false返回true表示您的数据已成功保存,返回false表示未保存...

答案 1 :(得分:0)

请尝试

SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString);

public int InserData(string abID, string fHitType, string DateOfHit, string TimeOfHit, string fEmpid)
{            
    SqlCommand oCommand = new SqlCommand("SP_insertData", oConnection);           
    oCommand.CommandType = CommandType.StoredProcedure;
    oCommand.Parameters.AddWithValue("@abID", abID);
    oCommand.Parameters.AddWithValue("@fHitType", fHitType);
    oCommand.Parameters.AddWithValue("@DateOfHit", DateOfHit);
    oCommand.Parameters.AddWithValue("@TimeOfHit", TimeOfHit);
    oCommand.Parameters.AddWithValue("@fEmpid", fEmpid);
    oConnection.Open();
    int Result = oCommand.ExecuteNonQuery();
    oConnection.Close();
    return Result;
}

如果返回类型1,则表示不成功插入