今天想總結一下上周老師講的用Connection對象連接字符串實現登錄的demo。 也想將代碼熟悉一下。 首先在sql server中建好表,我只設置了兩個字段 :usrName和PSD。
接下來在vs中建一個login的windows窗體應用程序(其他的類型程序也可以,代碼是一樣的) 當然需要先了解一下給對象之間的關系,如下圖: 先在下窗體設計器中加上按鈕,文本框等,界面如下:
然后添加按鈕,雙擊添加函數,代碼如下,已經添加注釋,寫在了登錄按鈕里面。
PRivate void btuLogin_Click(object sender, EventArgs e) { string usrName = this.userName.Text.Trim(); string psd = this.psd.Text.Trim(); string connectionstring = @"Server = AFOC-1702201437/SQLEXPRESS; User ID=sa; passWord = 0903. ; Database = Test"; SqlConnection conn = new SqlConnection(); conn.ConnectionString = connectionstring; conn.Open(); //MessageBox.Show("數據庫打開成功!"); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select * from userInfo where userName ='" + usrName + " 'and psd = '" + psd + "';"; cmd.Connection = conn; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); int i = 0; try { da.Fill(ds); i = ds.Tables[0].Rows.Count; } catch (Exception exp) { MessageBox.Show(exp.Message.ToString()); } if (ds.Tables[0].Rows.Count > 0) { MessageBox.Show("登錄成功!"); } else { MessageBox.Show("UserName or Password has error!"); this.userName.Text = string.Empty; this.psd.Text = string.Empty; return; } conn.Close(); }“`
新聞熱點
疑難解答