C# - 无法使用新的 SqlConnection() 连接到本地 ACCDB 文件



执行一个大学项目,该项目需要一个从本地访问数据库文件存储和输出数据的应用程序。

到目前为止,我对 C# 知识很少,但我对如何编写代码以及什么是函数和方法有基本的了解。

我在StackOverflow和其他网站上查找了很多关于此类问题的不同问题,但我找不到解决问题的方法。

这是代码 -

private void search_db(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
string search_query = search_input.Text;
conn.ConnectionString = "Data Source=D:/Projects/WIP/8515/Academy/Travel Agency C#/Hotel_Agency/Hotel_Database.accdb;";
conn.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Customers WHERE (name LIKE @query) OR (EGN LIKE @query)", conn);
command.Parameters.Add(new SqlParameter("query", search_query));
// Create new SqlDataReader object and read data from the command.
using (SqlDataReader reader = command.ExecuteReader())
{
// while there is another record present
while (reader.Read())
{
// write the data on to the screen
Console.WriteLine(String.Format("{0} t | {1} t | {2} t | {3}",
// call the objects from their index
reader[0], reader[1], reader[2], reader[3]));
}
}
}
}

在给定代码的第 6 行上,如果我的 ConnectionString 提供了我已经三重检查并确认的数据来源是正确的,我唯一不确定的是我应该使用哪种类型的斜杠,因为 Windows 目录中的默认 \ 斜杠被误认为是 Visual Studio 的转义,而使用/斜杠就可以了。

问题是与数据库的连接总是失败并出现此错误

类型为"System.Data.SqlClient.SqlException"的未处理异常 发生在系统数据中.dll

其他信息:网络相关或特定于实例的错误 在建立与 SQL Server 的连接时发生。服务器是 未找到或无法访问。验证实例名称是否为 正确和那个 SQL

以下是我们用于此应用程序的命名空间的完整列表

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

我尝试将提供程序关键字添加到连接字符串,但这会导致有关不受支持的关键字的另一个错误,因为据称System.Data.SqlClient命名空间会自动设置提供程序。

任何关于可能导致这种情况的帮助,我们将不胜感激!

PS:对于我提出的任何进一步缺乏知识,我深表歉意,我真的是C#编程的新手,但我发现它非常有趣和令人兴奋,并希望了解更多信息。

你在这里犯了一个常见的错误。命名空间System.Data.SqlClient(SqlConnection,SqlCommand等)中定义的类只能与Sql Server数据库系统(Full,Express或LocalDb)通信。它们不能使用 Access 数据库。

对于此数据库,您应该使用System.Data.OleDb命名空间中的类(OleDbConnection、OleDbCommand 等)。这些类了解连接字符串以访问 Access 数据库,并且可以打开和使用它。

所以你的代码应该是:

....
using System.Data.OleDb;
private void search_db(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = ......
conn.Open();
string cmdText = @"SELECT * 
FROM Customers 
WHERE ([name] LIKE @q1) OR (EGN LIKE @q2)";
using(OleDbCommand command = new OleDbCommand(cmdText, conn))
{
command.Parameters.Add("@q1", OleDbType.VarWChar).Value = search_query;
command.Parameters.Add("@q2", OleDbType.VarWChar).Value = search_query;
using (OleDbDataReader reader = command.ExecuteReader())
{
....
}
}
}
}

使用 OleDb 要记住的一件重要事情是你有位置参数。参数不是通过其名称识别的,而是通过它们在查询文本中的位置来识别的。因此,如果您有两个参数占位符,即使它们用于相同的值,您也需要在集合中放置两个参数。一个用于第一个占位符,一个用于第二个占位符。当您具有不同值的占位符时,这一点更为重要。您需要按照查询文本中预期的确切顺序添加值。

最新更新