gpt4 book ai didi

c# - 数据读取器初始化(再次)

转载 作者:行者123 更新时间:2023-12-02 19:14:24 28 4
gpt4 key购买 nike

我收到数据读取器初始化错误。我知道这个问题以前已经回答过很多次了,但这些案例似乎不适合我的情况。错误消息开头为“执行读取器:连接属性尚未初始化。”

程序:

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。有什么建议吗?

最佳答案

您从未将 SqlCommand 与连接关联起来:

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

没有它,命令(以及扩展的数据读取器)不知道任何要使用的连接。

关于c# - 数据读取器初始化(再次),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33177448/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com