简体   繁体   中英

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

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

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.

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]

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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