using Sqystem.Data;
using System.Data.SqlClient;
using System.Configuration;
//引用一个库Ststem.configuration
//修改根目录的web.config文件
<configuration>//最外层节点
......
<connectionStrings>
<add name="connString" connectionString = "Sqerver=.;DataBase=StudentManage;Uid=sa;Pwd=scale2018@">
</connectionStrings>
......
</configuration>
//数据库通用访问类
class SQLHelper
{
//数据库连接字符串
private static string connString = ConfigurationManager.ConnectionStrings["connString"].ToString();
//写入日志文件
public void WriteLog(string msg)
{
FileStream fs = FileStream("1.log",fileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.writeLine(DateTime.Now.ToString()+" "+ msg);
sw.Close();
fs.Close();
}
//数据库更新
public static int Update(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlConnection cmd = new SqlCommand(sql,conn);
try
{
conn.Open();
return cmd.ExecuteNoQuery();
}
catch(Exception ex)
{
WriteLog("执行更新时发生异常"+ex.Message);
throw ex;
}
finally
{
conn.Close();
}
}
public static object GetSingleResult(string sql)
{
Sqlconnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql,conn);
try
{
conn.Open();
return cmd.ExecuteScalar();
}
catch(Exception ex)
{
WriteLog("执行单一结果查询"+ex.message);
throw ex;
}
finally
{
conn.Close();
}
}
//返回结果集
public static SqlDataReader GetReader(string sql)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sql,conn);
try
{
conn.Open();
retrun cmd.ExecuteReader(CommandBehavior.CloseConnection);//不能在此关闭连接
}
catch(Exception ex)
{
WriteLog("读取结果集发生异常"+ex.message);
throw ex;
}
}
//带参数的存储过程
public static int Update(string sqlOrProcedureName,SqlParameter[]param,bool isProcedure)
{
SqlConnection conn = new SqlConnection(connString);
SqlConnection cmd = new SqlCommand(sqlOrProcedureName,conn);
if(isProcedure)
{
cmd.CommandType = CommmandType.StoredProcedure;
}
try
{
conn.Open();
cmd.Parameters.AddRang(param);
return cmd.ExecuteNoQuery();
}
catch(Exception ex)
{
WriteLog("执行更新时发生异常"+ex.Message);
throw ex;
}
finally
{
conn.Close();
}
}
}
//DAL调用数据访问模块
class AdminService
{
public UseInfo Login(UseInfo objUser)
{
string sql = "select UserName from UserTable where loginid=@LoginId and LoginPwn=@LoginPwn";
SqlParameter[] param = new SqlParameter[];
{
new SqlPrameter("@LoginId",UseInfo.LoginId),
new SqlParameter("@LoginPwd",UseInfo.LoginPwd)
};
try
{
SqlDataReader objReader = SQLHelper.GetReader(sql,param,false);
if(objReader.Read())
{
objUser.UserName = objReader["UserName"].ToString();
}
else
{
objUser = null;
}
objReader.Close();
}
catch(Exception ex)
{
throw new Exception("用户登录异常"+ex.message);
}
return objUser;
}
}
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。