日期:2014-05-17  浏览次数:20769 次

问一个关于c#web项目数据库连接的基础问题?
如题,我在Conn.cs中写了
public static string conn = "data source=PINGGUOSHUAI;initial catalog=yinhang;persist security info=true;user id=sa;password=123456";  //静态构造一个数据库打开的连接,ConfigurationSettings.AppSettings[0]为web.config配置文件中声明的数据库连接字符串

        public static int ExecuteCommand(string safeSql)
        {
            SqlConnection sqlConnection = new SqlConnection(conn);
            int result;
            try
            {
                sqlConnection.Open();
                SqlCommand sqlCommand = new SqlCommand(safeSql, sqlConnection);
                result = sqlCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                throw ex;
            }
            finally
            {
                sqlConnection.Close();
            }
            return result;
        }
这样的连接数据库语句,还用在web.config中再写一遍吗?两个文件里面在哪个里面写比较好点?

------解决方案--------------------
写在配置文件中方便用户在不重新编译源代码的情况下修改连接。否则每次更换机器名、用户名、密码,用户都得让你重新编译一次代码,烦不烦?