2015-10-16 73 views
1

我得到一个DataReader初始化错误。我知道这已被回答了很多次,但这些情况似乎不符合我的情况。错误消息开始“执行读取器:连接属性尚未初始化”。数据读取器初始化(再次)

程序:

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

namespace BookList 

{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      SqlConnection dataConnection = new SqlConnection(); 
      dataConnection.ConnectionString = "Integrated Security = true; Initial Catalog = BIBLIOGRAPHY;Data Source = JBSHAPIRO-PC\\SQLEXPRESS"; 

      dataConnection.Open(); 
      Console.Write("Enter author's name: "); 
      string person = Console.ReadLine(); 




      SqlCommand datacommand = new SqlCommand(); 
      datacommand.CommandText = "SELECT AUTHOR, TITLE, YEAR, KEYWORDS 

FROM BOOKS WHERE AUTHOR = ' " + person + " ' "; 


      Console.WriteLine("About to Execute: {0}\n\n", 

datacommand.CommandText); 


      SqlDataReader dataReader = datacommand.ExecuteReader(); 

      while (dataReader.Read()) 
      { 
       string author1 = dataReader.GetString(0); 
       string title1 = dataReader.GetString(1); 
       int year1 = dataReader.GetInt32(2); 
       string keywords1 = dataReader.GetString(3); 

       Console.WriteLine(
        "Author: {0}\n, Title: {1}\n, Year: {2}\n; Key Words: {4)\n\n", 
       author1, title1, year1, keywords1); 
       dataReader.Close(); 
      } 
      dataConnection.Close(); 
     } 
    } 
} 

代码工作与C#3写一个不同的数据库,但现在我想用C#6 有什么建议?

+0

有趣知道为什么有关格式错误代码,并不太正确的说法问题“的代码工作与C#3写了不同的数据库”有这么多upvotes。我看到[MCVE]问题如何能够确定(和不SQL注入)... –

回答

2

你做

SqlCommand datacommand = new SqlCommand(); 

但我没有看到一个

datacommand.Connection = dataConnection; 

这种方式既不是命令也不是SqlDataReader的知道什么连接使用。

附注:我会stronly意见,对动态SQL添加参数。

这是一个良好的开端,以防止SQL注入

SqlCommand datacommand = new SqlCommand("SELECT AUTHOR, TITLE, YEAR, KEYWORDS FROM BOOKS WHERE AUTHOR = @AUTHOR", dataConnection); 

datacommand.Parameters.AddWithValue("@AUTHOR", person); 
3

你永远不相关的SqlCommand与连接:

SqlCommand datacommand = new SqlCommand(); 
datacommand.Connection = dataConnection; 

没有它,命令(通过扩展数据读取器)有没有任何使用连接的知识。

+0

这不能真正回答(即使是完全正确的)为“代码工作与C#3写了不同的数据库” ...不知道如何投票。 –

+1

@AlexeiLevenkov:我的猜测是关于在别处工作的代码声明可能是错误的。非常相似的代码完全可以在另一个环境中“工作”。但问题中的确切代码会在问题中产生错误。 – David

0

感谢所有为你的答案。其实这个程序来自Microsoft Press的C#2008 Step By Step。它可以与旧版本的C#一起工作。 在提交问题后,我注意到您确实需要在SQL语句中指定连接。

我感谢大家的帮助。 塞利纳斯