c# - 如何修复“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;
}
}
}
解决方案
推荐阅读
- java - 如何使用 Saxon XSLT 转换每个 xml 节点?
- python - python 日期时间到 np.datetime64
- c# - 从 Controller 调用 SignalR Core Hub 方法时的连接 ID
- css - 切换后,更改此菜单中字形的最有效的纯 CSS 方法是什么?
- python - 有没有办法在 python 中找到 *.csv 存在?
- mysql - MySQL IF ELSE 真假
- java - 检查键盘输入是否为空或不是“Y”或不是“X”
- recursion - 递归局部视图在 Razor 视图中渲染树结构是否存在任何潜在风险
- wix - 在延迟的自定义操作中读取复选框值
- django - Django:从哪里清除 URL 中的值?