C#用SqlCilent模式连接数据库实例
面试中经常会考到的题,这里以数据表[test]为例:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"server=(local);" +
"user id=;" +
"password=;" +
"initial catalog=TestDB;";
try
{
conn.Open();
}
catch( Exception ex)
{
Debug.WriteLine( ex.Message);
return;
}
SqlCommand command = new SqlCommand(
"select * from test", conn);
SqlDataReader reader;
reader = command.ExecuteReader();
while( reader.Read() == true)
{
for( int i = 0 ; i < reader.FieldCount; i++)
{
object objData = reader.GetValue(i);
Debug.WriteLine( objData.ToString());
}
}
reader.Close();
conn.Close();
三思而后定