2010年4月28日 星期三

ASP.NET C # 連接資料庫 SQL Server

using System.Data.SqlClient;

string connetionString = "Data Source=data_source(server_name);Initial Catalog=db_name;User ID=account;Password=pwd";
//string connetionString = "server=IP; database=資料庫名稱; uid=帳號; pwd=密碼; Initial Catalog=資料庫名稱";
//string connectionString = GetConnectionString(); 也可以自己寫個方法把連線字串內容包起來

SqlConnection connection = new SqlConnection(connetionString);
try
            {
                connection.Open();
                Response.Write("Connection Open !");
                Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
                Console.WriteLine("State: {0}", connection.State);
                string sqlText = "Select * from products"
                SqlCommand sqlCmd = new SqlCommand(sqlText , connection );
                //SqlDataAdapter adpt = = new SqlDataAdapter(sqlCmd);
                //DataSet dataset = new DataSet();
                //adpt.Fill(dataset , table_name);
                //DataView dataview = new DataView(dataset .Tables[0]);
                connection.Close();
            }
            catch (Exception ex)
            {
                Response.Write("Connection Fail !");
            }

沒有留言: