简体   繁体   English

.NET和SQL Server数据库链接

[英].NET and sql server database link

I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. 我是.NET中的真正菜鸟,而且我正尝试将一个简单的命令行应用程序(在C#中)与SQL Server数据库链接。 I'm now able to connect the program with the database but not to recover the data that are in it. 现在,我可以将程序与数据库连接,但无法恢复其中的数据。 Here is my code : 这是我的代码:

using System;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            string connectionString = GetConnectionString();
            string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = connection.CreateCommand();
                command.CommandText = queryString;
                try
                {
                    connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    int i = 0;
                    while (reader.Read())
                    {
                        i++;
                        Console.WriteLine("Field "+i);
                        Console.WriteLine("\t{0}",reader[0]);
                    }
                    reader.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //Console.WriteLine("Hello world");
            string x = Console.ReadLine();
        }

        static private string GetConnectionString()
        {
            return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
                + "Integrated Security=SSPI";
        }
    }
}

But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method. 但是,当我运行它时,即使我的表不为空(我在sql server studio中也看到过),我也无法通过使用read()方法恢复数据。 What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid). 到目前为止,我所做的是:尝试使用伪造的数据表更改数据表的名称:找不到数据表(因此sql server数据库和programm之间的链接似乎有效)。

I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that). 我正在sql服务器中使用Windows身份验证,如果正在更改任何内容,则不知道...(再次:我对所有这些都很陌生)。

Thanks ! 谢谢 !

Your code should work. 您的代码应该可以工作。
A possible cause is: You are looking at a different database. 可能的原因是:您正在查看其他数据库。
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code. 如果在VS中使用Server Explorer且连接字符串与代码中使用的连接字符串不同,则这是很常见的。

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

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