我是.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;
}
}
答案 0 :(得分:0)
存储过程通过SqlCommand执行,运行插入/更新语句没有太大区别。
SqlCommand cmd = new SqlCommand("sp_name", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@SomeParameter", SqlDbType.VarChar).Value = someValue;
con.Open();
cmd.ExecuteNonQuery();
您应该考虑为IDisposable
类实现DataAccess
,以便在不需要时处理数据库资源。