SQLHelper 的基本使用

首先是下载SQLHelper,修改SQLHelper 的连接配置信息,

private static string GetConnection()
        {
            string strConnection = "";
            try
            {
                strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["ServerConnectionString"].ConnectionString;
                if (String.IsNullOrEmpty(strConnection)) throw new Exception("ConnectionString is NullorEmpty!"); else return strConnection;
            }
            catch (Exception e)
            {
                throw new Exception("Error in GetConnectionString!!! Source:" + e.Source.ToString() + " Message:" + e.Message.ToString());
            }
        }
ExecuteScalar 

用来执行一行SQL语句,有多个重载函数;可以依据自己的需要配置:返回值是个Object 类型,可以执行的类型包括,sql 语句,存储过程,

public string Add(Model.Group_Info groupobj)
        {
            try
            {
                SqlParameter[] parameters ={
                                      new SqlParameter("@GName",groupobj.GName),
                                      new SqlParameter("@GOrder",groupobj.GOrder)
                                      };

                string commandText = "if exites (select 1 from Group_Info where GName=@GName)" +
                                     "begin" +
                                     " select 'exists';" +
                                     "end" +
                                     "else " +
                                     "begin" +
                                     " insert Group_Info (GName,GOrder) values (@GName,@GOrder)" +
                                     " select 'ok';"+
                                     "end";

                return SQLHelper.ExecuteScalar(commandText, parameters).ToString();
            }
            catch (Exception ex)
            {
                MyDAL.Error.WriteErrorLog(ex);
                return "error";
            }
        }

ExecuteNonQuery 的使用

可以用来执行,新增,修改,删除,返回值为int 类型,表示影响的行数。

public int Update(Model.Group_Info groupobj, int gid)
        {
            SqlParameter[] parameters = { 
                                        new SqlParameter("@ID",gid),
                                        new SqlParameter("@GName",groupobj.GName),
                                        new SqlParameter("@GOrder",groupobj.GOrder)
                                        };

            string commandText = "update Group_Info set GName=@GName,GOrder=@GOrder where id=@ID";

            try
            {
                return SQLHelper.ExecuteNonQuery(commandText, parameters);
            }
            catch (Exception ex)
            {
                MyDAL.Error.WriteErrorLog(ex);
                return 0;
            }
        }


你可能感兴趣的:(C#编程)