SqlException:'='附近的语法不正确

时间:2014-09-15 17:03:32

标签: c# sql exception ado.net connection-string

我正在学习一些基础课,我正在尝试最简单的例子,但是我在阅读器执行过程中遇到了SQL异常。

类型'System.Data.SqlClient.SqlException的未处理异常...'='附近的语法不正确。

以下是代码的核心:

    static void Main(string[] args)
    {
        string connectionString = "Server=(localdb)\\v11.0;Integrated Security=true;AttachDBFileName=C:\\Users\\james\\Documents\\Visual Studio 2013\\Projects\\Day8_6\\Database1.mdf;";
        string queryString = "SELECT * FROM [Customers]";

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand(connectionString, connection);

                connection.Open();

                // *** ERROR ON FOLLOWING LINE
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    Console.WriteLine("\t{1}\t{2}", reader[1], reader[2]);
                }

                connection.Close();
        }

        Console.ReadLine();

    }

Suggetions?谢谢!

2 个答案:

答案 0 :(得分:4)

此:

SqlCommand command = new SqlCommand(connectionString, connection);

需要:

SqlCommand command = new SqlCommand(queryString, connection);

答案 1 :(得分:2)

您正在SqlCommand构造函数而不是sql查询中传递连接字符串:

SqlCommand command = new SqlCommand(queryString, connection);