简体   繁体   English

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

[英]C# - unable to connect to a local ACCDB file with new SqlConnection()

Doing a university project that requires an application that stores and outputs data from a local access DB file. 做一个大学项目,需要一个应用程序来存储和输出本地访问DB文件中的数据。

So far I have very little C# knowledge but I have a basic understanding of how to write code and what functions and methods are. 到目前为止,我对C#的了解很少,但是对如何编写代码以及什么是函数和方法有基本的了解。

I have looked up a lot of different questions on StackOverflow and other sites about this kind of issue, yet I could not find a solution to my problem. 我在StackOverflow和其他站点上查询了很多有关此类问题的问题,但找不到解决方案。

Here is the code - 这是代码-

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]));
            }
        }
    }
}

on line 6 of the given code, if my ConnectionString which provides the data souce which I have triple checked and confirmed is proper, the only thing I'm not sure is what type of slash should I use, since the default \\ slash from windows directories gets mistaken for an escape by Visual Studio, while with the / slash its ok. 在给定代码的第6行上,如果我提供了经过三重检查并确认的数据源的ConnectionString是正确的,则我不确定的是我应该使用哪种类型的斜杠,因为Windows中的默认\\斜杠Visual Studio将目录误认为是转义,而用/斜杠可以。

The problem is the connection to the DB always fails with this error 问题是与数据库的连接总是失败,并显示此错误

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll System.Data.dll中发生了类型为'System.Data.SqlClient.SqlException'的未处理的异常

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. 附加信息:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。 The server was not found or was not accessible. 服务器未找到或无法访问。 Verify that the instance name is correct and that SQL 验证实例名称正确和SQL

Here is the full list of the namespaces we are using for this application 这是我们用于此应用程序的名称空间的完整列表

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;

I have tried adding provider keyword to the connection string but that leads to another error about an unsupported keyword, since the System.Data.SqlClient namespace is allegedly automatically setting a provider. 我尝试将provider关键字添加到连接字符串中,但这会导致另一个与不受支持的关键字有关的错误,因为System.Data.SqlClient命名空间据称自动设置了提供程序。

Any help as to what might be causing this is appreciated! 任何有关可能造成这种情况的帮助,我们将不胜感激!

PS: I apologize for any further lack of knowledge I present, I really am new to C# programming, but I find it quite interesting and exciting, and would like to learn more. PS:对于我现在所缺少的知识,我深表歉意,我确实是C#编程的新手,但是我觉得它很有趣,令人兴奋,并且想了解更多。

You are making a common mistake here. 您在这里犯了一个常见错误。 The classes defined in the namespace System.Data.SqlClient (SqlConnection, SqlCommand etc.) are able to talk only with a Sql Server database system (Full, Express or LocalDb). 在命名空间System.Data.SqlClient中定义的类(SqlConnection,SqlCommand等)只能与Sql Server数据库系统(Full,Express或LocalDb)通信。 They cannot work with an Access database. 他们不能使用Access数据库。

For this database you should use the classes in the System.Data.OleDb namespace (OleDbConnection, OleDbCommand etc.) These classes understand the connectionstring to reach an Access database and can open and work with it. 对于此数据库,您应该使用System.Data.OleDb命名空间中的类(OleDbConnection,OleDbCommand等)。这些类理解连接字符串以访问Access数据库,并且可以打开并使用它。

So your code should be: 因此,您的代码应为:

....
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())
            {
               ....
            }
        }
    }
}

An importat thing to remember with OleDb is that you have positional parameters. OleDb要记住的一个重要事项是您具有位置参数。 The parameters are not recognized by their name but by their position in the query text. 这些参数不能通过名称识别,而可以通过它们在查询文本中的位置来识别。 So if you have two parameters placeholder, even if they are for the same value, you need to put two parameters in the collection. 因此,如果您有两个参数占位符,即使它们具有相同的值,也需要在集合中放置两个参数。 One for the first placeholder and one for the second placeholder. 一个用于第一个占位符,一个用于第二个占位符。 This is even more important when you have placeholders for different values. 当您具有不同值的占位符时,这一点尤为重要。 You need to add the values in the exact order in which they are expected in the query text. 您需要按照查询文本中期望的确切顺序添加值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM