废话不多说直接上代码
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 AdoTwo
11 {
12 public partial class FLogin : Form
13 {
14 public FLogin()
15 {
16 InitializeComponent();
17 }
18
19 private void btnOk_Click(object sender, EventArgs e)
20 {
21 string tname = txtName.Text.Trim();//a
22 string tpwd = txtPwd.Text.Trim();//b
23 //判断用户名密码是否正确其实就是去数据库查询有没有一条数据,
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 Name=@ass and Pwd=@add", 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 }