如何使用存储过程获取和设置

时间:2015-03-24 10:52:40

标签: c# sql-server-2008 stored-procedures

我一直在使用SQL Server 2008和C#已经有一段时间了但总是在与OOP方面挣扎。我通常按​​如下方式编写Insert语句。以下摘录是我正在玩的一个AJAX网站

SqlCommand scCommand = new SqlCommand("spLocationsCreate", APMConn);
scCommand.CommandType = CommandType.StoredProcedure;

scCommand.Parameters.Add("@LocationCode", SqlDbType.VarChar, 5).Value = txtLocationCode.Text;
scCommand.Parameters.Add("@Location", SqlDbType.NVarChar, 100).Value = txtLocation.Text;

scCommand.Connection.Open();
scCommand.ExecuteNonQuery();
scCommand.Connection.Close();

上面的工作并向数据库添加了一条记录,我以为我开始使用上面的类--Set和Get。写了以下课程

public class clsLocations
{
    public clsLocations()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    private string _LocationCode;
    private string _Locations;

    public string LocationCode
    {
        get { return _LocationCode; }
        set { _LocationCode = value; }
    }

    public string Locations
    {
        get { return _Locations; }
        set { _Locations = value; }
    }
}

我理解上述内容,但我正在努力如何将它与存储过程一起使用以及如何调用它。我在网上看过很多文章,但很多人使用直接SQL而不是存储过程和参数

非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

常见的模式是在clsLocations类上使用Save()方法,该方法调用存储过程并相应地填充参数。 E.g:

public void Save(SqlConnection apmConn)
{
    SqlCommand scCommand = new SqlCommand("spLocationsCreate", apmConn);
        scCommand.CommandType = CommandType.StoredProcedure;
        scCommand.Parameters.Add("@LocationCode", SqlDbType.VarChar, 5).Value = this.LocationCode;
        scCommand.Parameters.Add("@Location", SqlDbType.NVarChar, 100).Value = this.Locations;
        scCommand.Connection.Open();
        scCommand.ExecuteNonQuery();
        scCommand.Connection.Close();
}

为了将来的调查,您可能需要考虑从模型类中分离出数据库代码。您可以使用ORM,例如EntityFramework。或者是一个简单的数据访问层,由静态函数组成,用于调用存储过程。

答案 1 :(得分:0)

认为我已经破解了.....这有效,但请告知我是否做错了

我的班级位于顶部,并将其添加到代码

之下
public void SaveLocation(SqlConnection APMConn)
{
    SqlCommand scCommand = new SqlCommand("spLocationsCreate", APMConn);
    scCommand.CommandType = CommandType.StoredProcedure;
    scCommand.Parameters.Add("@LocationCode", SqlDbType.VarChar, 5).Value = _LocationCode;
    scCommand.Parameters.Add("@Location", SqlDbType.NVarChar, 100).Value = _Locations;
    scCommand.Connection.Open();
    scCommand.ExecuteNonQuery();
    scCommand.Connection.Close();
}

在我的主程序中有以下

protected void InsertNewLocations(SqlConnection conn)
{
    clsLocations NewLoc = new clsLocations();
    NewLoc.LocationCode = txtLocationCode.Text;
    NewLoc.Locations = txtLocation.Text;
    NewLoc.SaveLocation(APMConn); 
}
相关问题