ADO.NET三个核心对象的简要说明

SqlConnection //连接字符串

SqlCommand //执行sql命令的对象

SqlDataReader //读取数据库中的记录

注意除了SqlConnection要记得关闭外 DataReader也要即使关闭,否则在下次使用未关闭的DataReader时候会出错。

示例代码如下:


class Program
    {

        
/// <summary>
        
/// 应用程序的入口
        
/// </summary>
        
/// <param name="args"></param>
        
/// <returns></returns>
        static void Main(string[] args)
        {
            
string connectionString = GetConnectString();
            
string queryString = "select * from person where id = 2";
            
//string queryString = "delete from person where id = 2;";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command 
= connection.CreateCommand();
                command.CommandText 
= queryString;
                command.CommandType 
= CommandType.Text;

                
try
                {
                    connection.Open();
                    
//command.ExecuteNonQuery();//执行非查询命令
                    SqlDataReader reader = command.ExecuteReader()//读取数据命令;
                    while (reader.Read())
                    {
                        
for (int i = 0; i < reader.FieldCount; i++)
                        {
                            Console.Write(
"{0}\t", reader[i]);
                        }
                        Console.WriteLine();
                    }
                    reader.Close();
                }
                
catch (System.Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.Read();
        }
        
        
/// <summary>
        
/// 连接字符串
        
/// </summary>
        
/// <returns></returns>
        public static string GetConnectString()
        {
            
return "Data Source=(local);Init ial Catalog=mytestdb;"
           
+ "Integrated Security=SSPI";
        }

 

posted @ 2009-01-03 22:30  vieri122  阅读(1505)  评论(4编辑  收藏  举报