【问题标题】:how to retrieve data from sql server to DataTable using c#如何使用c#将数据从sql server检索到DataTable
【发布时间】:2016-05-09 09:58:51
【问题描述】:
    string j = "Data Source=FUJITSU-PC\\SQLEXPRESS;Initial Catalog=attendance_system;Integrated Security=True";
    DataTable dt = new DataTable();
    using (SqlConnection cn = new SqlConnection(j))
    {
        SqlCommand cmd = new SqlCommand("select dbo.faculty_status.username from dbo.faculty_status", cn);
        cn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        dt.Load(dr);
        cn.Close();
    }
    int x = dt.Rows.Count;
    foreach (DataRow row in dt.Rows)
    {
        foreach (var item in row.ItemArray)
        {
            string xx = item.ToString();
        }
    }

MySQL server database table

我使用了这个代码,但它没有显示我想要的第一行值 它给了我像----

13-24516-2

【问题讨论】:

  • 错误是什么?
  • 你用xx做什么?由于它是局部变量,它可能会被第二行覆盖?
  • 我想使用 xx 变量打印我的值
  • 我在这里看不到该代码。您可以编辑帖子并提供该代码吗?
  • @KrishnaChaithanyaMuthyala ....我的代码----

标签: c# sql-server sql-server-2012


【解决方案1】:

我认为问题在于您的阅读方式。 试试这个:

    string j = "Data Source=FUJITSU-PC\\SQLEXPRESS;Initial Catalog=attendance_system;Integrated Security=True";
    using (SqlConnection cn = new SqlConnection(j))
    {
        SqlCommand cmd = new SqlCommand("select dbo.faculty_status.username from dbo.faculty_status", cn);
        cn.Open();
        using (var reader = cmd.ExecuteReader())
        {
            while(reader.Read())
            {
                Console.WriteLine(reader["username"]);
            }
        }
    }

让我知道它是否有效!

【讨论】:

  • 很高兴知道...请尝试使用存储过程,而不是像这样的直接命令...
【解决方案2】:

它给你最后一行。 XX 字符串首先加载第一个结果,然后在第二行上用第二行覆盖第一行,只要有行就继续。

如果你想显示第一行,你可以使用类似的东西:

    DataTable dt = new DataTable();
    string xx = dt.Rows[0].ToString();

foreach (DataRow row in dt.Rows)
{
        foreach (var item in row.ItemArray)
        {
            Console.WriteLine(item.ToString());
        }
}

dt.Rows[要检索的行]

【讨论】:

  • 它不起作用。它仍然给我第二行..第二行之后它工作正常..它给我 3,4,5 等等
【解决方案3】:

试试这个代码示例:-

SqlCommand cmd = new SqlCommand("select dbo.faculty_status.username from dbo.faculty_status", cn);
DataTable dt = new DataTable();
SqlDataAdapter mda = new SqlDataAdapter(cmd);
mda.Fill(dt);

让我知道它是否有效!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多