简体   繁体   English

C#从数据库中读取数据

[英]Read data from a database in C#

I have created a table name glossary in a database named ChatBotDataBase in SQL Server.我在 SQL Server 中名为ChatBotDataBase的数据库中创建了一个表名词汇表。 I want to read the data in a special column of the table.我想读取表格特殊列中的数据。

To do so, I have written this code:为此,我编写了以下代码:

    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());
    } 

But there is an error in last line.但是最后一行有错误。

The error is :错误是:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll. System.Data.dll 中发生类型为“System.IndexOutOfRangeException”的未处理异常。

And here is a print screen of the mentioned table:这是上述表格的打印屏幕:在此处输入图片说明

Can anyone help please?有人可以帮忙吗?

Looks like you are confusing the Datatable called table with your database table in your sql server.看起来您将名为tableDatatable table与 sql server 中的数据库表混淆了。 In your image you show us the glossary table in your sql server, not the DataTable called table .在您的图像中,您向我们展示了 sql server 中的glossary表,而不是名为tableDataTable table

You get this error because you create an empty DataTable called table with DataTable table = new DataTable() but you didn't even fill your table .因为你创建一个空的您得到这个错误DataTable称为tableDataTable table = new DataTable()但你甚至没有填满你的table That's why it doesn't have any rows by default.这就是默认情况下它没有任何行的原因。

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

Also use using statement to dispose your SqlConnection , SqlCommand and SqlDataAdapter .还使用using语句来处理您的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());
   }
}

Below code will help you下面的代码会帮助你

    sda.SelectCommand.CommandText = "SELECT * FROM glossary";
    DataTable table = new DataTable();
    sda.Fill(table , "glossary");
    MessageBox.Show(table.Rows[0].ItemArray[3].ToString());

You haven't executed the query or populated the table.您尚未执行查询或填充表。 It is empty.它是空的。 It has no columns and no rows.它没有列也没有行。 Hence the error.因此错误。

Frankly, though, I strongly suggest using a typed class model, not any kind of DataTable.不过,坦率地说,我强烈建议使用类型化的类模型,而不是任何类型的 DataTable。 With tools like "dapper", this can be as simple as:使用像“dapper”这样的工具,这可以很简单:

var list = conn.Query<Glossary>("SELECT * FROM glossary").ToList();

With

public class Glossary {
    public int Id {get;set}
    public string String1 {get;set} // horrible name!
    ....
    public int NumberOfUse {get;set}
}
using System.Data.Odbc;

OdbcConnection con = new OdbcConnection("<connectionstring>");

OdbcCommand com = new OdbcCommand("select * from TableX",con);

OdbcDataAdapter da = new OdbcDataAdapter(com);
DataSet ds = new DataSet();

da.Fill(ds,"New");

DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables["New"];

you can get the connection string from:您可以从以下位置获取连接字符串:

http://www.connectionstrings.com/ http://www.connectionstrings.com/

Dear kindly first fill your table with the data.亲爱的,请先用数据填充您的表格。 And you should use checks because if there is no data then you get a proper message.check is below..您应该使用检查,因为如果没有数据,那么您会收到一条正确的消息。检查如下..

if(dt.Rows.Count > 0)
     MessageBox.Show(table.Rows[0].ItemArray[3].ToString());
else if(dt.Rows.Count > 0)
      MessageBox.Show("Table is empty");

And other advice is that you should display data into DataGrid.... Displaying data from Database into a message box is not a good programming approach..其他建议是您应该将数据显示到 DataGrid 中……将数据库中的数据显示到消息框中并不是一种好的编程方法。

For displaying DataTable into DataGrid in C# is as simple as below.在 C# 中将 DataTable 显示到 DataGrid 中非常简单,如下所示。

        SqlCommand cmd = new SqlCommand("select * from student",con);
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        dt.TableName = "students";
        da.Fill(dt);
        dataGridView1.DataSource =dt;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM