//获取连接字符串,在未引用System.Configuration时可以手动拼写引用 //private static string _connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["StockDB"].ConnectionString; private static string _connectionString = ConfigurationManager.ConnectionStrings["StockDB"].ConnectionString; SqlConnection conn = null; SqlCommand cmd = null; public AllocationBusiness() { conn = new SqlConnection(_connectionString); cmd = conn.CreateCommand(); }
//通用数据库访问类 //strconn为获取的连接字符串 Utilities.DbUtility.DbAccess DBdataStatistics = new Utilities.DbUtility.DbAccess(strconn, Utilities.DbUtility.DbProviderType.SqlServer);
在EF模板生成的数据库连接文件中,也可以用这种方式获取:如生成类名为:StockDBEntities
using (StockDBEntities db2 = new StockDBEntities()) { db2.Database.CommandTimeout = 200;//响应时间,可根据情况不写 //因连接配置已经模板生成,此处获取连接字符串的方式就是:db2.Database.Connection.ConnectionString Utilities.DbUtility.DbAccess db = new Utilities.DbUtility.DbAccess(db2.Database.Connection.ConnectionString, Utilities.DbUtility.DbProviderType.SqlServer); }
本地操作日志及错误日志的写法:(要添加引用Utilities.dll)
/// <summary> /// 操作日志写入 /// </summary> /// <param name="username">登录人</param> /// <param name="logContent">日志内容</param> public static void WriteLog(string username,string logContent) { //此处以竖线分割操作人和内容,这个可随着实际情况编写,参数也根据项目需要自定 Utilities.LogHelper.LogHelper.WriteLog(username + "|" + logContent, Utilities.LogHelper.Log4NetLevel.Debug); } /// <summary> /// 错误日志写入 /// </summary> /// <param name="logContent">日志内容</param> public static void WriteLog(string logContent) { Utilities.LogHelper.LogHelper.WriteLog(logContent, Utilities.LogHelper.Log4NetLevel.Error); }
webconfig数据库连接配置:
<configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> <connectionStrings> <add name="Conn" connectionString="Data Source=192.168.30.104;Initial Catalog = 数据库名;User Id = sa;Password = 123;Connect Timeout=5000" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>