Frank Feng

Friday, July 01, 2005

Accessing database by hand in C#

string connString = "data source=localhost;initial catalog=...;user id=sa;password=...";
SqlConnection myConnection = new SqlConnection(connString);

try{
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();

string sqlString = "select id, fname, lname from AddressBook";
myCommand.CommandType = CommandType.Text;
myCommand.CommandText = sqlString;

SqlDataReader myReader = myCommand.ExecuteReader();

// print title
System.Console.Write("ID ");
System.Console.Write(" First Name ");
System.Console.WriteLine(" Last Name");
System.Console.WriteLine(" Mobile");
System.Console.WriteLine("--------------------------------------");

while(myReader.Read()) {
System.Console.Write(myReader.GetInt32(0) + " ");
System.Console.Write(myReader.GetString(1) + " ");
System.Console.WriteLine(myReader.GetString(2));
}

myConnection.Close();
}catch(Exception ex) {
System.Console.WriteLine("Error occured while accessing data");
System.Console.WriteLine(ex.ToString());
}

0 Comments:

Post a Comment

<< Home