【问题标题】:I have created a generic database class to call database (SQL Server) from C#我创建了一个通用数据库类来从 C# 调用数据库(SQL Server)
【发布时间】:2016-11-27 08:34:17
【问题描述】:

我是 .net 的新手。请帮我在这里添加什么?如何添加存储过程?我的目标是将DataAccess 类保留在一个项目中,并在其他项目中作为.dll 使用。在其他项目中,我只想调用 dbclass 并添加参数,只执行方法。请帮帮我

我的代码:

public class DataAccess
{
    string commandString;
    string commandType;
    private static string ConnectionStrings = ConfigurationManager.ConnectionStrings["studentConnectionString"].ToString();

    SqlConnection connection = new SqlConnection(ConnectionStrings);
    SqlCommand command = new SqlCommand();

    DataTable dt = new DataTable();

    public String commandStrings
    {
        get { return commandString; }
        set { commandString = value; }
    }

    public String commandTypes
    { 
        get { return commandType; }
        set { commandType = value; }
    }

    public void addparameters(String name, Object value)
    {
        command.Parameters.AddWithValue(name, value);
    }

    public DataTable Exec(String Query) 
    {
        DataTable datatable = new DataTable();

        if (connection.State != ConnectionState.Open)
        {
            connection.Close();
            connection.Open();
        }

        try
        {               
            SqlDataAdapter adapter = new SqlDataAdapter(Query, connection);
            adapter.Fill(datatable);
            return datatable;
        }
        catch (Exception e)
        { }
        finally
        { 
             connection.Close();
        }

        return null;
    } 

    public int Execute(String Query)
    {
        int AffectedRows = 0;
        command.CommandText = Query;
        command.Connection = connection;

        if (connection.State != ConnectionState.Open)
        {   
            connection.Close();
            connection.Open();
        }

        try
        {              
            AffectedRows = command.ExecuteNonQuery();
            return AffectedRows;
        }
        catch (Exception e)
        { }
        finally
        {   
            connection.Close();
        }

        return 0;
    }
}

【问题讨论】:

    标签: c# asp.net sql-server database


    【解决方案1】:

    存储过程通过SqlCommand执行,运行insert/update语句没有太大区别。

        SqlCommand cmd = new SqlCommand("sp_name", con); 
    
        cmd.CommandType = CommandType.StoredProcedure;        
        cmd.Parameters.Add("@SomeParameter", SqlDbType.VarChar).Value = someValue;
    
        con.Open();
        cmd.ExecuteNonQuery();     
    

    您应该考虑为DataAccess 类实现IDisposable,以便在不需要时处理数据库资源。

    【讨论】:

    • 这是我所期待的
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多