How to save SELECT sql query results in an array in C# Asp.net

后端 未结 6 608
时光取名叫无心
时光取名叫无心 2020-12-14 17:36

I have wrote this query to get some results, if I want to save the results in an array what I have to do? I want to use the values which are in col1 and col2 in an IF state

6条回答
  •  醉酒成梦
    2020-12-14 17:58

    Pretty easy:

     public void PrintSql_Array()
        {
            int[] numbers = new int[4];
            string[] names = new string[4];
            string[] secondNames = new string[4];
            int[] ages = new int[4];
    
            int cont = 0;
    
            string cs = @"Server=ADMIN\SQLEXPRESS; Database=dbYourBase; User id=sa; password=youpass";
            using (SqlConnection con = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = "SELECT * FROM tbl_Datos";
                    con.Open();
    
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    da.Fill(dt);
    
                    foreach (DataRow row in dt.Rows)
                    {
                        numbers[cont] = row.Field(0);
                        names[cont] = row.Field(1);
                        secondNames[cont] = row.Field(2);
                        ages[cont] = row.Field(3);
    
                        cont++;
                    }
    
                    for (int i = 0; i < numbers.Length; i++)
                    {
                        Console.WriteLine("{0} | {1} {2} {3}", numbers[i], names[i], secondNames[i], ages[i]);
                    }
    
                    con.Close();
                }
            }
        }
    

提交回复
热议问题