为什么我的查询不会运行?

时间:2013-12-04 00:16:05

标签: c# sql sql-server-ce

我有很多类似的查询可以工作,我不知道为什么这个不会:

我一跑完就得到:

  

未处理的类型异常   发生'System.Data.SqlServerCe.SqlCeException'   System.Data.SqlServerCe.dll

... command.ExecuteNonQuery();

有任何明显的错误吗?

public void BorrowMovie(int memberCardNumber)
{
    string connectionString = @"Data Source=|DataDirectory|\VideoStoreDB.sdf";
    SqlCeConnection connection = new SqlCeConnection(connectionString);

    connection.Open();
    SqlCeCommand command = new SqlCeCommand(
        "UPDATE Customer SET NumberBorrowedMovies = NumberBorrowedMovies+1 " +
        "WHERE MemberCardNR = @mcn)", connection);    
    command.Parameters.AddWithValue("@mcn", memberCardNumber);      
    command.ExecuteNonQuery();
    connection.Close();

    Console.WriteLine("Movie was borrowed!");
    Console.ReadLine();
}

1 个答案:

答案 0 :(得分:6)

你有不平衡的括号:

SqlCeCommand command = new SqlCeCommand(
    "UPDATE Customer SET NumberBorrowedMovies = NumberBorrowedMovies+1 " +
    "WHERE MemberCardNR = @mcn", connection);    

此外,您应该使用using块:

public void BorrowMovie(int memberCardNumber)
{
    string connectionString = @"Data Source=|DataDirectory|\VideoStoreDB.sdf";
    using (SqlCeConnection connection = new SqlCeConnection(connectionString))
    {

    connection.Open();
    using (SqlCeCommand command = new SqlCeCommand(
        "UPDATE Customer SET NumberBorrowedMovies = NumberBorrowedMovies+1 " +
        "WHERE MemberCardNR = @mcn)", connection))
    {   
    command.Parameters.AddWithValue("@mcn", memberCardNumber);      
    command.ExecuteNonQuery();
    // connection.Close(); no longer needed
    } // command
    } // connection
    Console.WriteLine("Movie was borrowed!");
    Console.ReadLine();
}