gpt4 book ai didi

c# - C#从数据库中读取数据

转载 作者:搜寻专家 更新时间:2023-10-30 21:38:46 24 4
gpt4 key购买 nike

我在 SQL Server 中名为 ChatBotDataBase 的数据库中创建了一个表名词汇表。我想读取表格特殊列中的数据。

为此,我编写了这段代码:

    private void button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = @"Data Source=shirin;Initial Catalog=ChatBotDataBase;
Integrated Security=True";
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = new SqlCommand();
sda.SelectCommand.Connection = sc;

sda.SelectCommand.CommandText = "SELECT * FROM glossary";

DataTable table = new DataTable();
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}

但是最后一行有错误。

错误是:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll.

这是上述表格的打印屏幕:enter image description here

有人可以帮忙吗?

最佳答案

看起来您将名为 tableDatatable 与 sql server 中的数据库表混淆了。在您的图片中,您向我们展示了 sql server 中的 glossary 表,而不是名为 tableDataTable

您收到此错误是因为您使用 DataTable table = new DataTable() 创建了一个名为 table 的空 DataTable 但您没有 < em>甚至 填充您的。这就是默认情况下它没有任何行的原因。

SqlCommand cmd = new SqlCommand("SELECT * FROM glossary");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(table);

也可以使用 using statement处理您的 SqlConnectionSqlCommandSqlDataAdapter

using(SqlConnection sc = new SqlConnection(conString))
using(SqlCommand cmd = sc.CreateCommand())
{
cmd.CommandText = "SELECT * FROM glossary";
...
using(SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable table = new DataTable();
sda.Fill(table);

if(dt.Rows.Count > 0)
MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
}
}

关于c# - C#从数据库中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27654700/

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