天天看點

C#連接配接sqlserver資料庫

       當在C#語言中,連接配接sql資料庫的時候,常用到sqlconnection建立與資料庫的連接配接。 文法如下:

       String sqlcon = "***";//這裡是一個字元串,具體跟資料庫的驗證方式有關。

//sql server 身份驗證 連接配接字元串

private string ConnstrSqlServer = "server=伺服器名稱;uid=登入名稱;pwd=登入密碼;database=資料庫名稱";

//windows 身份驗證連接配接字元串

private string ConnstrWindows = "server=伺服器名稱;database=資料庫名稱;Trusted_Connection=SSPI";

       SqlConnection connection = new SqlConnection(sqlcon);

例如:

SqlConnection connection = new SqlConnection("server=(local);database=dotNET_lab;Trusted_Connection=SSPI");

//windows驗證方式 。

SqlConnection connection = new SqlConnection("server=(local);uid=sa;password=sa;database=dotNET_lab");

//混合驗證方式 。

然後,

            try {

                connection.Open();

                SqlCommand command = new SqlCommand("select count(*) from admin where username='"+username+"' and password='"+password+"'",connection);

                SqlDataReader reader = command.ExecuteReader();

                while(reader.Read())

                {

                    n = reader.GetInt32(0);//n是在之前定義的,如果n>0,顯然就存在這樣一個使用者。                  

                }

                //Console.WriteLine(reader.GetString(1));

            }

            catch(SqlException ex) {

                Console.WriteLine(ex.Message);

            }

            finally {

                connection.Close();

            }