我在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());
}
但最后一行有个错误。
错误是:
System.Data.dll中发生“System.IndexAutoFrangeException”类型的未处理异常。
下面是上述表格的打印屏幕:
有人能帮忙吗?
最佳答案
看起来您把名为Datatable
的table
与SQL Server中的数据库表混淆了。在您的图像中,您显示的是SQL Server中的glossary
表,而不是名为DataTable
的table
表。
您得到这个错误是因为您用DataTable
创建了一个名为table
的空DataTable table = new DataTable()
,但是您甚至没有填充您的table
。这就是为什么默认情况下它没有任何行。
SqlCommand cmd = new SqlCommand("SELECT * FROM glossary");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(table);
还可以使用
using
statement处理您的SqlConnection
、SqlCommand
和SqlDataAdapter
。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/