2013-12-10 69 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