简体   繁体   English

如何使用C#将数据从SQL Server检索到DataTable

[英]how to retrieve data from sql server to DataTable using c#

    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 MySQL服务器数据库表

I used this code it wors but it does not show me my desire first row value it givs me out put like---- 我使用了它很讨厌的这段代码,但是它并没有显示我想要的第一行值,它给了我这样的提示----

13-24516-2 13-24516-2

I think the problem is the way you are reading. 我认为问题在于您的阅读方式。 Try this: 尝试这个:

    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"]);
            }
        }
    }

Let me know if it works! 让我知道它是否有效!

It gives you the last row. 它给您最后一行。 the XX string is first loaded with the first results, afterwards on the second row it overwrites the first row with the second row, this goes on as long as there is rows. XX字符串首先加载第一个结果,然后在第二行上用第二行覆盖第一行,只要有行就继续执行。

if you want the first rows the be displayed you could use somthing like: 如果要显示第一行,可以使用类似以下的内容:

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

or 要么

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

dt.Rows[the row you want to retrieve] dt.Rows [您要检索的行]

Try this code example:- 试试这个代码示例:

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

Let me know if it works! 让我知道它是否有效!

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

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