有没有办法可以在执行SQL事务时重用这些代码,我想让它成为一个方法,所以我可以把参数放到执行其他存储过程, 你能帮助我设计一个好的编码结构吗?
try {
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("InsertUser2Sp", con) {
CommandType = CommandType.StoredProcedure
}) {
cmd.Parameters.AddWithValue("@UserID", useridStr);
cmd.Parameters.AddWithValue("@Firstname", firstnStr);
cmd.Parameters.AddWithValue("@Middlename", middleNstr);
cmd.Parameters.AddWithValue("@Lastname", lastnStr);
cmd.Parameters.AddWithValue("@UserAge", ageInt);
cmd.Parameters.AddWithValue("@HomeAddress", homeaddStr);
con.Open();
cmd.ExecuteNonQuery();
}
}
} catch (Exception ex) {
MessageBox.Show("Could not connect to database. Check settings. " + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message);
}
}
答案 0 :(得分:0)
我将在这里分享一个通用方法。您需要做的就是构建一个具有与SP中的参数相同的属性名称(包括个案)的对象。
protected internal string GetSingleValue_String(String spname, Object entity)
{
Object res = new Object();
String conString = String.Empty;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand(spname, con);
cmd.CommandType = CommandType.StoredProcedure;
if (entity != null)
{
SqlCommandBuilder.DeriveParameters(cmd);
PropertyInfo entitymember = default(PropertyInfo);
foreach (SqlParameter _param in cmd.Parameters)
{
if (_param.Direction == ParameterDirection.Input)
{
entitymember = entity.GetType().GetProperty(_param.ParameterName.Replace("@", ""));
var entityValue = entitymember.GetValue(entity, null);
String _paramvalue = entityValue != null ? entityValue.ToString() : null;
_param.Value = (string.IsNullOrEmpty(_paramvalue) || _paramvalue == string.Empty ? null : _paramvalue);
}
}
}
res = cmd.ExecuteScalar();
cmd.Connection.Close();
entity = null;
cmd = null;
if(res==null)
res = "";
else if (String.IsNullOrEmpty(res.ToString()))
res = "";
return res.ToString();
}
}
因此,在您的示例中,创建一个与SP参数具有相同定义的新类。
class NewClass()
{
public string UserID { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
public string UserAge { get; set; }
public string HomeAddress { get; set; }
}
并将调用这样的方法。
var newClass = new NewClass
{
UserID = "UserId",
Firstname = "Firstname",
Middlename = "Middlename",
Lastname = "Lastname",
UserAge = "UserAge",
HomeAddress = "HomeAddress"
}
var res = GetSingleValue_String("InsertUser2Sp", newClass);
不要介意返回类型。