我有以下连接字符串,以下两种方法处理不同的存储过程:我觉得这段代码有点冗长,想知道是否有可能减少可能的冗余?
是否有更精简的方法来使用相同的连接字符串调用各个方法。
简而言之; 我只是问是否有办法用更少的代码来做我正在做的事情?
我在一个名为的类中拥有所有这些Database
:
class Database
{
public static Int32 intReturnCode { get; set; }
public static string DatabaseStatus { get; set; }
static string source =
@"Server=MyServer;Database=MyDatabase;Integrated Security=True; Timeout=30";
public static void InsertTracking(string UserID, string Department)
{
try
{
using (SqlConnection databaseConnection = new SqlConnection(source))
{
using (SqlCommand cmdSQL = new SqlCommand("usp_InsertUser", databaseConnection))
{
cmdSQL.CommandType = CommandType.StoredProcedure;
cmdSQL.Parameters.Add(new SqlParameter("@UserID", SqlDbType.NChar, 8));
cmdSQL.Parameters["@UserID"].Value = UserID;
cmdSQL.Parameters["@UserID"].Direction = ParameterDirection.Input;
cmdSQL.Parameters.Add(new SqlParameter("@Department", SqlDbType.NChar, 4));
cmdSQL.Parameters["@Department"].Value = Department;
cmdSQL.Parameters["@Department"].Direction = ParameterDirection.Input;
cmdSQL.Parameters.Add(new SqlParameter("@ReturnCode", SqlDbType.Int));
cmdSQL.Parameters["@ReturnCode"].Direction = ParameterDirection.ReturnValue;
databaseConnection.Open();
cmdSQL.ExecuteNonQuery();
intReturnCode = Convert.ToInt16(cmdSQL.Parameters["@ReturnCode"].Value);
databaseConnection.Close();
}
}
}
catch (Exception ex)
{
DatabaseStatus = ex.Message;
}
}
public static int InitializeDatabase()
{
try
{
using (SqlConnection databaseConnection = new SqlConnection(source))
{
using (SqlCommand cmdSQL = new SqlCommand("usp_InitializeDatabase", databaseConnection))
{
cmdSQL.CommandType = CommandType.StoredProcedure;
cmdSQL.Parameters.Add(new SqlParameter("@ReturnCode", SqlDbType.Int));
cmdSQL.Parameters["@ReturnCode"].Direction = ParameterDirection.ReturnValue;
databaseConnection.Open();
cmdSQL.ExecuteNonQuery();
intReturnCode = Convert.ToInt16(cmdSQL.Parameters["@ReturnCode"].Value);
databaseConnection.Close();
}
}
}
catch (Exception ex)
{
DatabaseStatus = ex.Message;
}
return intReturnCode;
}
}