简体   繁体   中英

Retrieve more data from a SQL Server database

I'm taking 2 variables from SQL table 'Zupanije', but I don't know how to use them. I tried the code below but it takes the key twice, instead of key and value.

sqlCmd.CommandText = "SELECT COUNT(*) From Zupanije";
conn.Open();
int count = (int)sqlCmd.ExecuteScalar();
conn.Close();

sqlCmd.CommandText = "SELECT Naziv, Sifra From Zupanije";
conn.Open();
using (var zupanijeReader = sqlCmd.ExecuteReader())
{
    while (zupanijeReader.Read())
    {
        for (int i=0; i <= count; i++)
        { 
            izborZupanija.Add(zupanijeReader[i].ToString(), 
                              Convert.ToDouble(zupanijeReader[i]));
        }
    }
}
conn.Close();

The reader exposes an array of columns through its indexer. You are picking the same column twice using variable i . You should use the helper methods on the reader to pull the values, ie reader.GetString(0) and reader.GetDouble(1) if the data types are already correct in the db.

I agree with @leetibbett. The SqlDataReader will iterate over each result when you call Read(). You then pull out each column value use the SqlDataReader.GetString and SqlDataReader.GetDouble methods, passing in the column index as an argument.

sqlCmd.CommandText = "SELECT Naziv, Sifra From Zupanije";
conn.Open();
using (var zupanijeReader = sqlCmd.ExecuteReader())
{
    while (zupanijeReader.Read())
    {
        izborZupanija.Add(zupanijeReader.GetString(0), zupanijeReader.GetDouble(1));
    }
}
conn.Close();

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