我收到了datareader初始化错误。我知道之前已经多次回答过,但这些情况似乎不符合我的情况。错误消息开始“执行Reader:连接属性尚未初始化。”
该计划:
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 :(得分:3)
您从未将SqlCommand
与连接相关联:
SqlCommand datacommand = new SqlCommand();
datacommand.Connection = dataConnection;
没有它,命令(以及扩展数据阅读器)不知道任何连接使用。
答案 1 :(得分:2)
你做
SqlCommand datacommand = new SqlCommand();
但我没有看到
datacommand.Connection = dataConnection;
这样,命令和SqlDataReader都不知道要使用什么连接。
旁注:我强烈建议在动态SQL上添加参数。
这是防止Sql Injection
的良好开端SqlCommand datacommand = new SqlCommand("SELECT AUTHOR, TITLE, YEAR, KEYWORDS FROM BOOKS WHERE AUTHOR = @AUTHOR", dataConnection);
datacommand.Parameters.AddWithValue("@AUTHOR", person);
答案 2 :(得分:0)
感谢大家的回答。实际上,该程序来自Microsoft Press的C#2008 Step by Step。它适用于旧版本的C#。 提交问题后,我注意到你需要在新的规范中指定SQL语句中的连接。
谢谢大家的帮助。 塞利纳斯