標籤:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Data.SqlClient; 6 using System.Drawing; 7 using System.Text; 8 using System.Windows.Forms; 9 10 namespace AdoTwo11 {12 public partial class FLogin : Form13 {14 public FLogin()15 {16 InitializeComponent();17 }18 19 private void btnOk_Click(object sender, EventArgs e)20 {21 string tname = txtName.Text.Trim();//a22 string tpwd = txtPwd.Text.Trim();//b23 //判斷使用者名稱密碼是否正確其實就是去資料庫查詢有沒有一條資料,24 //這條資料是使用者名稱等於使用者輸入的使用者名稱,25 //並且26 //密碼等於使用者輸入的密碼的一條資料27 SqlConnection conn = new SqlConnection("server=.;database=heimablog;uid=sa;pwd=suncoder");28 string sql=string.Format("select count(id) from Student where Name=‘{0}‘ and Pwd=‘{1}‘",tname,tpwd);29 SqlCommand cmd = new SqlCommand(sql, conn);30 //cmd.Connection = conn;31 //cmd.CommandText = "";32 conn.Open();33 34 //SqlDataReader dr = cmd.ExecuteReader();35 //if (dr.HasRows) 36 //{37 // MessageBox.Show("登陸成功");38 //}39 //while (dr.Read())40 //{41 // Console.WriteLine(dr[1].ToString());//+dr["Name"],dr.GetString(1));42 //}43 44 object obg = cmd.ExecuteScalar();45 int res = Convert.ToInt32(obg);46 if (res > 0) { MessageBox.Show("登陸成功"); }47 else { MessageBox.Show("登陸失敗"); }48 }49 50 private void btnLoginPara_Click(object sender, EventArgs e)51 {52 SqlConnection conn = new SqlConnection("server=.;database=heimablog;uid=sa;pwd=suncoder");53 SqlCommand cmd = new SqlCommand("select count(id) from Student where [email protected] and [email protected]", conn);54 55 //第一種寫法56 //SqlParameter sp = new SqlParameter("@ass", txtName.Text.Trim());57 //SqlParameter sp2 = new SqlParameter("@add", txtPwd.Text.Trim());58 59 //cmd.Parameters.Add(sp);60 //cmd.Parameters.Add(sp2);61 62 //第二種寫法,特殊情況下報錯63 //cmd.Parameters.Add(new SqlParameter("@ass", txtName.Text.Trim()));64 //cmd.Parameters.Add(new SqlParameter("@add", txtPwd.Text.Trim()));65 66 //第三種寫法67 //SqlParameter[] spa = new SqlParameter[]{68 // new SqlParameter("@ass", txtName.Text.Trim()),69 // new SqlParameter("@add", txtPwd.Text.Trim())70 //};71 //cmd.Parameters.AddRange(spa);72 73 //第四種寫法74 //cmd.Parameters.AddWithValue("@ass", txtName.Text.Trim());75 //cmd.Parameters.AddWithValue("@add", txtPwd.Text.Trim());76 77 //第五種寫法,參數可以為輸出參數78 //SqlParameter sp = new SqlParameter("@ass", SqlDbType.NVarChar);79 //SqlParameter sp2 = new SqlParameter("@add", SqlDbType.Char);80 //sp.Value = txtName.Text.Trim();81 //sp2.Value = txtPwd.Text.Trim();82 //cmd.Parameters.Add(sp);83 //cmd.Parameters.Add(sp2);84 85 //第六種寫法86 SqlParameter sp = new SqlParameter("@ass", SqlDbType.NVarChar) { Value = txtName.Text.Trim() };87 SqlParameter sp2 = new SqlParameter("@add", SqlDbType.Char) { Value = txtPwd.Text.Trim() };88 cmd.Parameters.Add(sp);89 cmd.Parameters.Add(sp2);90 91 conn.Open();92 93 MessageBox.Show(cmd.ExecuteScalar().ToString());94 95 }96 }97 }
C# ADO.NET參數查詢