ADO.NET三個核心物件的簡要說明

iDotNetSpace發表於2009-01-04

SqlConnection //連線字串

SqlCommand //執行sql命令的物件

SqlDataReader //讀取資料庫中的記錄

注意除了SqlConnection要記得關閉外 DataReader也要即使關閉,否則在下次使用未關閉的DataReader時候會出錯。

示例程式碼如下:

ADO.NET三個核心物件的簡要說明
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtclass Program
    {

        
/// 
        
/// 應用程式的入口
        
/// 
        
/// 
        
/// 
        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();
        }
        
        
/// 
        
/// 連線字串
        
/// 
        
/// 
        public static string GetConnectString()
        {
            
return "Data Source=(local);Init ial Catalog=mytestdb;"
           
+ "Integrated Security=SSPI";
        }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-526496/,如需轉載,請註明出處,否則將追究法律責任。

相關文章