【发布时间】:2021-10-15 10:03:33
【问题描述】:
我正在尝试从我的 SQL Server 数据库中获取一些值,我可以通过以下方式连接到它:
SqlConnection conx = new SqlConnection();
SqlConnection conx4 = new SqlConnection("Data Source=.\\Sistema_Deci;Initial Catalog=sistema_decisiones_financieras;Persist Security Info=True;User id=sa;Password=somepassword;timeout=120;");
conx = conx4;
conx.Open();
conx.Close();
到目前为止它运行良好,但是当我尝试从中获取值时出错,代码如下:
try
{
SqlCommand cmd2 = new SqlCommand("SELECT * FROM Ordenes_Servicios", conx);
SqlDataReader reader1;
DataTable dtordenes = new DataTable();
conx.Open();
SqlDataAdapter sqlDA = new SqlDataAdapter(cmd2.ToString(), conx.ConnectionString);
sqlDA.Fill(dtordenes); // <--- at this point the error occurs
conx.Close();
}
catch(Exception ex)
{}
例外是:
System.Data.SqlClient.SqlException (0x80131904):在 sys.servers 中找不到服务器“系统”。验证是否指定了正确的服务器名称。如有必要,执行存储过程 sp_addlinkedserver 将服务器添加到 sys.servers。
到目前为止,我已经在 SQL Server 上尝试过这个来查看服务器的名称,显然结果中没有任何“系统”服务器,但是我不明白为什么它试图连接到“系统” ' 而不是 'Sistema_Deci'
select name from sys.servers
哦,我的 Visual Studio 是 2017(与 2019 相同的问题)并运行 SQL Server 2019 Express,因为我无法安装 2014,这是我迄今为止一直在使用的版本(我知道为什么,但它在安装时开始抛出错误2014)。
我找到了一种可行的方法,但这不是我试图对其进行编程的方式,因为将所有内容映射出来需要大量额外的工作
SqlCommand cmd2 = new SqlCommand("SELECT * FROM Ordenes_Servicios", conx);
SqlDataReader reader1;
DataTable dtordenes = new DataTable();
dtordenes.Columns.Add("ID");
dtordenes.Columns.Add("Cliente");
conx.Open();
reader1 = cmd2.ExecuteReader();
while (reader1.Read())
{
string temp = reader1["ID_Reporte"].ToString();
string temp2 = reader1["Cliente"].ToString();
dtordenes.Rows.Add(temp, temp2);
}
【问题讨论】:
-
将
SqlDataAdapter sqlDA = new SqlDataAdapter(cmd2.ToString(), conx.ConnectionString);更改为SqlDataAdapter sqlDA = new SqlDataAdapter(cmd2); -
我笑得很厉害,我不敢相信,但这完全解决了问题,你能解释一下为什么会出现这个问题吗?
-
您正在执行
new SqlDataAdapter(cmd2.ToString(), conx.ConnectionString);,这会将"System.Data.SqlClient.SqlCommand"和连接字符串传递给构造函数。第一个字符串应该是实际的 SQL 查询而不是"System.Data.SqlClient.SqlCommand"。 SqlDataAdapter 的另一个构造函数只接受SqlCommand。你只需要使用它。 docs.microsoft.com/en-us/dotnet/api/…
标签: c# sql sql-server visual-studio runtime-error