1. 代码结果如下图所示:
????
2. TblPersonBll.cs中的代码:
????public class TblPersonBll
{
public bool IncAgeByAutoId(int autoId)
{
TblPersonDal dal=new TblPersonDal();
return dal.IncAgeByAutoId(autoId) > 0;
}
}
3. TblPersonDal.cs中的代码:
????public class TblPersonDal
{
public int IncAgeByAutoId(int autoId)
{
string sql = "update TblPerson set age=age+1 where autoId=@id";
return SqlHelper.ExcuteNonQuery(sql, CommandType.Text, new SqlParameter("@id", autoId));
}
}
4. frmIncAge.cs中的代码:
????private void button1_Click(object sender, EventArgs e)
{
TblPersonBll bll=new TblPersonBll();
int autoId = int.Parse(textBox1.Text.Trim());
if (bll.IncAgeByAutoId(autoId))
{
MessageBox.Show("ok!");
}
else
{
MessageBox.Show("not ok!");
}
}
5. SqlHelper.cs中的代码:
????public static class SqlHelper
{
//获取连接字符串
private static string conStr = ConfigurationManager.ConnectionStrings["mysqlserver"].ConnectionString;
/// <summary>
/// 执行insert/delete/update方法
/// </summary>
/// <param name="sql"></param>
/// <param name="cmdType"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static int ExcuteNonQuery(string sql, CommandType cmdType, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 执行返回单个值方法
/// </summary>
/// <param name="sql"></param>
/// <param name="cmdType"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static object ExecuteScalar(string sql, CommandType cmdType, params SqlParameter[] pms)
{
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
con.Open();
return cmd.ExecuteScalar();
}
}
?
}
/// <summary>
/// 执行返回SqlDaraReader方法
/// </summary>
/// <param name="sql"></param>
/// <param name="cmdType"></param>
/// <param name="pms"></param>
/// <returns></returns>
public static SqlDataReader ExecuteDataReader(string sql, CommandType cmdType, params SqlParameter[] pms)
{
SqlConnection con = new SqlConnection(conStr);
?
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = cmdType;
if (pms != null)
{
cmd.Parameters.AddRange(pms);
}
try
{
con.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
con.Close();
con.Dispose();
throw;
}
}
}
?
public static DataTable ExecuteDataTable(string sql, CommandType cmdType, params SqlParameter[] pms)
{
DataTable dt = new DataTable();
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conStr))
{
adapter.SelectCommand.CommandType = cmdType;
if (pms != null)
{
adapter.SelectCommand.Parameters.AddRange(pms);
}
adapter.Fill(dt);
return dt;
}
}
?
}
原文:http://www.cnblogs.com/taidou/p/4722231.html