void Main()
{
string connString;
connString = "Data Source=(local);Initial Catalog=Ochhi che guardano;Integrated Security=SSPI";
String sqlString;
try
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
sqlString = "SELECT Vare.varenavn";
sqlString += " FROM vare";
sqlString += " ORDER BY vare.varenavn";
SqlCommand cmd = new SqlCommand(sqlString, conn);
SqlDataReader reader =
cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (reader.HasRows)
{
reader.Read();
Console.WriteLine(reader.GetString(0));
}
reader.Close();
conn.Close();
}
catch (System.Data.SqlClient.SqlException e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I have this database, where i have a list of goods i need printed to a text file and saved and the heard drive. (vare = goods). But when i run this code, i get an error. My question is what i am doing wrong with this code and how i can save the list in a .txt file. I know how files are handled in C#, but not how to integrate it with my database.
I suspect that you are getting multiple rows back, and currently you are able to display only a single row. That is because you are not iterating through the reader. Try the following in place of you your if block.
If you want to store the data in a text file you can store each returned string in a list and then write that list to text file. So your code would be: