2013-12-10 68 views
0

這已經有一段時間了,因爲我搞砸了任何SQL,我正在嘗試構建一個Todo應用程序來學習一些ASP.Net與C#。我使用的是Visual Studio 2013以及它隨附的任何版本的SQL Express,都在本地。SQL異常錯誤C#ASP.Net

我有以下表todo_list,與下面的腳本製作,通過Visual Studio:

CREATE TABLE [dbo].[todo_list] (
    [id]  INT NOT NULL, 
    [task]  TEXT NOT NULL, 
    [complete] BIT NOT NULL, 
    [date]  DATE NOT NULL, 
    PRIMARY KEY CLUSTERED ([id] ASC) 
); 

當web應用程序啓動時,我試圖讓所有的記錄,其中completefalse。我假設我可以讀取/寫入complete列作爲true/false,因爲它的類型爲bit

我得到的時候下面的代碼去執行引發的異常...

private void Get_Tasks() 
    { 
     //Get the connection string 
     SqlConnection connection = new SqlConnection(); 
     connection.ConnectionString = System.Configuration.ConfigurationManager. 
      ConnectionStrings["Database1ConnectionString"].ConnectionString; 

     //Build SQL query 
     string query = "SELECT * FROM todo_list WHERE complete=False"; 
     System.Diagnostics.Debug.WriteLine(query); 

     //Build SQL Command Object 
     SqlCommand command = new SqlCommand(query, connection); 

     //Grab all uncompleted tasks from database 
     SqlDataReader cursor; 

     try 
     { 
      using(connection) 
      { 
       //Open and execute SQL stuffz... 
       connection.Open(); 
       cursor = command.ExecuteReader(); 

       //Get all the tasks 
       while (cursor.Read()) 
       { 
        //Build the task from record set 
        Todo task = new Todo(
         (int)cursor["id"], (string)cursor["task"], 
         (bool)cursor["complete"], (DateTime)cursor["date"]); 

        //Append to DOM 
        Page.ClientScript.RegisterStartupScript(this.GetType(), "alert" + UniqueID, "alert('About to append to DOM!');", true); 
        tasklist.InnerHtml = task.toHtml(); 
       } 

       //Close connection 
       connection.Close(); 
      } 
     } 
     catch (Exception e) 
     { 
      System.Diagnostics.Debug.WriteLine(e.ToString()); 
      connection.Close(); 
     } 

     //TODO - Grab all completed tasks from database 

    } 

cursor = command.ExecuteReader();執行引發的異常 -

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll'

System.Data.SqlClient.SqlException (0x80131904): Invalid column name 'False'.

我不知道爲什麼它將False作爲列名?

在此先感謝您的幫助!

回答

2

你的SQL查詢無效。你讀過錯誤信息了嗎?

您是否嘗試過在SQL Server Management Studio中運行(假設您使用SQL Server ...如果沒有,選擇交互式工具)?

您的查詢

select * 
from todo_list 
where complete = False 

爲[想,反正]從表todo_list選擇所有的行所在的表的兩列completeFalse是相等的。由於您的表中有沒有名爲False列,SQL Server的查詢編譯器爲您提供了明顯的錯誤::

Invalid column name 'False' 

SQL Server的數據類型bit是不是在C#意義上的boolean。它基本上是一個1位整數,其域爲{0,1}。你需要修改你的查詢是這樣的:

select * 
from todo_list 
where complete = 0 

的CLR雙向映射SQL Server的bit到CLR System.Boolean。如果bit列可以爲空,則任何SQL Server null值都將映射到唯一實例System.DbNull