首页 > 解决方案 > 如何修复“SQLException 未处理”System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的未处理异常

问题描述

运行此项目时出现错误

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

附加信息:A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

namespace Project.DAL
{

    public static class NativeSqlDb
    {
        public static string ConStr
        {
            get
            {
                return System.Configuration.ConfigurationManager.ConnectionStrings["Project.Properties.Settings.QuestionDbConnectionString"].ConnectionString;
            }
        }

        public static DataTable ExecuteReader(string sql)
        {
            SqlConnection con = new SqlConnection(ConStr);
            SqlCommand cmd = new SqlCommand(sql, con);
            DataTable dt = new DataTable("Dt");
            con.Open();  //Im having error on this part sqlexception was unhandle

            try
            {
                SqlDataReader reader = cmd.ExecuteReader();
                dt.Load(reader);
                reader.Close();
            }
            finally
            {
                con.Close();
            }
            return dt;
        }

        public static int ExecuteNonQuery(string sql)
        {
            SqlConnection con = new SqlConnection(ConStr);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            int sayi = 0;
            try
            {
                sayi = cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
            return sayi;
        }

        public static int ExecuteNonQuery(string sql, params SqlParameter[] param)
        {
            SqlConnection con = new SqlConnection(ConStr);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            int sayi = 0;
            foreach (SqlParameter p in param)
            {
                cmd.Parameters.Add(p);
            }
            try
            {
                sayi = cmd.ExecuteNonQuery();
            }
            finally
            {
                con.Close();
            }
            return sayi;
        }

        public static object ExecuteScalar(string sql)
        {
            SqlConnection con = new SqlConnection(ConStr);
            SqlCommand cmd = new SqlCommand(sql, con);
            con.Open();
            object o;
            try
            {
                o = cmd.ExecuteScalar();
            }
            finally
            {
                con.Close();
            }
            return o;
        }

    }
}

标签: c#

解决方案


推荐阅读