简体   繁体   English

Ado.net SQL连接

[英]Ado.net Sql Connection

I try to make Sql connection using Ado.Net. 我尝试使用Ado.Net建立Sql连接。 I create a ConsoleApplication and get the Name and UnitPrice values from my database. 我创建一个ConsoleApplication并从数据库中获取NameUnitPrice值。 After execution Console says can not open a connection. 执行后,控制台说无法打开连接。 What is wrong that I make ? 我做错了什么?

Here is my code: 这是我的代码:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class ConsoleApplication1
{
    static void Main()
    {
        string connectionString =
            "Data Source=EMINCIFTCI/EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040";


        string queryString =
            "SELECT Name, UnitPrice from dbo.Product "   
                + "ORDER BY UnitPrice DESC;";

        using (SqlConnection connection =
            new SqlConnection(connectionString))
        {

            SqlCommand command = new SqlCommand(queryString, connection);

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("\t{0}\t{1}",
                        reader[0], reader[1]);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
    }
}

我的资料库

Assuming EMINCIFTCI/EMIN is your computer name and (I assume) SQL Server instance, you need to swap the forward slash with a backslash (two, technically, unless you use a verbatim string). 假设EMINCIFTCI / EMIN是您的计算机名和(我假设)SQL Server实例,则需要将正斜杠与反斜杠交换(从技术上讲,除非您使用逐字字符串,否则在技术上是两个)。

So, use either 因此,使用

string connectionString =
            "Data Source=EMINCIFTCI\\EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040";

or 要么

string connectionString =
            @"Data Source=EMINCIFTCI\EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040";

You may want to review https://www.connectionstrings.com/ 您可能需要查看https://www.connectionstrings.com/

I think the connection string should be proper "Data Source=EMINCIFTCI/EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040;" 我认为连接字符串应该正确: "Data Source=EMINCIFTCI/EMIN;Initial Catalog=Ado;User ID=sa;Password=10203040;"

There should be semicolon in the end 最后应该有分号

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

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