sql连接字符串的位置

    public class SQLHelper
    {
        //private static string connStr = "Server = DESKTOP-IDK01B1\\SQLEXPRESS2014;DataBase = StudentManageDB;Uid = sa;Pwd = sa";
        private static string connStr = ConfigurationManager.ConnectionStrings["connStr"].ToString();

        /// <summary>
        /// 执行增删改方法
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static int Update(string sql)
        {
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand command = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return command.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                //将错误信息写入日志
                throw ex;
            }
            finally
            {
                conn.Close();
            }                              
        }
        public static object GetSingleResult(string sql)
        {
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand command = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return command.ExecuteScalar();
            }
            catch (Exception ex)
            {
                //将错误信息写入日志
                throw ex;
            }
            finally
            {
                conn.Close();
            }
        }
        /// <summary>
        /// 执行结果集查询
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public static SqlDataReader GetReader(string sql)
        {
            SqlConnection conn = new SqlConnection(connStr);
            SqlCommand command = new SqlCommand(sql, conn);
            try
            {
                conn.Open();
                return command.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception ex)
            {
                conn.Close();
                //将错误信息写入日志
                throw;
            }           
        }
    }

一般连接字符串是在SQLHelper类(DAL模块),会 生成DAL.dll文件,如果想改变连接字符串(在不同机器上,通常不同),则要改变dll。所以可以放置在app.config中

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
	<connectionStrings>
		<add name ="connStr"
		connectionString = "Server = DESKTOP-IDK01B1\SQLEXPRESS2014;DataBase = StudentManageDB;Uid = sa;Pwd = sa"/>
	</connectionStrings>
</configuration>
这样只需要修改app.config就可以了。但是这样会引入另一个问题,就是密码可现。这时可以采用加密的方式

猜你喜欢

转载自blog.csdn.net/sinat_41746494/article/details/80038182