简单登录设计增删改查

 获得数据,验证用户输入

View Code
            //获得数据,验证用户输入
            string yz1 = textBox1.Text.Trim();
            string yz2 = textBox2.Text.Trim();
            if (yz1==""||yz2=="")
            {

                MessageBox.Show("请正确输入用户名或密码");
                return;
            }
            if (!ValidatorHelper.IsLetter(yz1))
            {
                MessageBox.Show("用户名必须是英文字母");
                return;
            }

将获得的数据从数据库中查询比较

View Code
            try
            {
                Class2 cs = new Class2();
                bool it = cs.tof(textBox1.Text.Trim(),textBox2.Text.Trim());
                if (it)
                {
                    MessageBox.Show("登录成功");
                    Main main = new Main();
                    main.Show();
                }
                else
                {
                    MessageBox.Show("登录失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message );
            
            }

这里的都是sql语句,对数据库的连接

View Code
public  class Class2
    {
       public string cc = "Data Source=.;Initial Catalog=test;User ID=sa;Pwd=123";
        public bool tof(string UserName,string UserPassword)
        {

            string sql = string.Format("SELECT COUNT(*) FROM demoUsers WHERE UserName=@UserName AND UserPassword = @UserPassword");
            Class1 q = new Class1(cc);
            ArrayList paramlist = new ArrayList();
            paramlist.Add(q.CreateParameter("@UserName", UserName, DbType.String, 50));//参数化sql语句
            paramlist.Add(q.CreateParameter("@UserPassword", UserPassword, DbType.String, 50));//参数化sql语句
            IDataParameter[] param = (IDataParameter[])paramlist.ToArray(typeof(IDataParameter));
            object dt = q.ExecuteScalar(sql, param);
            int it = Convert.ToInt32(dt);
            return  it>0;
        }

       //读出数据,并列出在main界面
        public DataTable li(int UserId)
        {
            string sql = string.Format("SELECT * FROM demoUsers WHERE UserId=@UserId");
            Class1 q = new Class1(cc);
            ArrayList paramlist = new ArrayList();
            paramlist.Add(q.CreateParameter("@UserId", UserId, DbType.Int32 , 4));
            IDataParameter[] param = (IDataParameter[])paramlist.ToArray(typeof(IDataParameter));
            return q.testDataTable(sql, param);
        }

    }

对数据库的操作,复制过来的,还没自己写出来过,其中用了dataSet

View Code
  1 using System;
  2 using System.Data;
  3 using System.Data.Common;
  4 using System.Data.SqlClient;
  5 
  6 
  7 namespace _111
  8 {
  9     public class Class1
 10     {
 11         private string connstr="" ;
 12         public Class1(string abc)
 13         { connstr = abc; }
 14         #region Execute
 15         /// <summary>
 16         /// 执行sql语句
 17         /// </summary>
 18         /// <param name="sql">sql语句</param>
 19         public void Execute(string sql)
 20         {
 21             using (SqlConnection conn = new SqlConnection(connstr))
 22             {
 23                 using (SqlCommand cmd = new SqlCommand(sql, conn))
 24                 {
 25                     try
 26                     {
 27                         conn.Open();
 28                         int v = cmd.ExecuteNonQuery();
 29                     }
 30                     catch (Exception e)
 31                     {
 32                         throw new Exception(e.Message + sql, e);
 33                     }
 34                 }
 35             }
 36         }
 37         #endregion
 38 
 39         #region ExecuteNonQuery
 40         /// <summary>
 41         /// 执行sql语句返回命令影响的行数
 42         /// </summary>
 43         /// <param name="sql">sql语句</param>
 44         /// <param name="param">参数组</param>
 45         /// <returns>返回命令影响的行数</returns>
 46         public int ExecuteNonQuery(string sql, IDataParameter[] param)
 47         {
 48             using (SqlConnection conn = new SqlConnection(connstr))
 49             {
 50                 using (SqlCommand cmd = new SqlCommand(sql, conn))
 51                 {
 52                     try
 53                     {
 54                         conn.Open();
 55                         AttachParameters(cmd, param);
 56                         int v = cmd.ExecuteNonQuery();
 57                         cmd.Parameters.Clear();
 58                         return v;
 59                     }
 60                     catch (Exception e)
 61                     {
 62                         throw new Exception(e.Message + sql, e);
 63                     }
 64                 }
 65             }
 66         }
 67         #endregion
 68 
 69         #region ExecuteScalar
 70         /// <summary>
 71         /// 执行sql语句
 72         /// </summary>
 73         /// <param name="sql">sql语句</param>
 74         /// <param name="param">参数组</param>
 75         /// <returns>返回第一行的第一列</returns>
 76         public object ExecuteScalar(string sql, IDataParameter[] param)
 77         {
 78             using (SqlConnection conn = new SqlConnection(connstr))
 79             {
 80                 using (SqlCommand cmd = new SqlCommand(sql, conn))
 81                 {
 82                     try
 83                     {
 84                         conn.Open();
 85                         AttachParameters(cmd, param);
 86                         object v = cmd.ExecuteScalar();
 87                         cmd.Parameters.Clear();
 88                         return v;
 89                     }
 90                     catch (Exception e)
 91                     {
 92                         throw new Exception(e.Message + sql, e);
 93                     }
 94                 }
 95             }
 96         }
 97         #endregion
 98 
 99         #region ExecuteIdentity
100         /// <summary>
101         /// 执行sql语句 并返回自增字段值
102         /// </summary>
103         /// <param name="sql">SQL语句</param>
104         /// <param name="param">参数组</param>
105         /// <returns>自增列值</returns>
106         public  object ExecuteIdentity(string sql, IDataParameter[] param)
107         {
108             using (SqlConnection conn = new SqlConnection(connstr))
109             {
110                 using (SqlCommand cmd = new SqlCommand())
111                 {
112                     try
113                     {
114                         conn.Open();
115                        // SqlTransaction trans = conn.BeginTransaction();
116                         //PrepareCommand(cmd, conn, trans, CommandType.Text, sql, param);
117                        // cmd.ExecuteScalar();
118                        // cmd.Parameters.Clear();
119                         cmd.CommandText = sql +";select @@IDENTITY";//SELECT SCOPE_IDENTITY()
120                       //  trans.Commit();
121                         object v = cmd.ExecuteScalar();
122                         cmd.Parameters.Clear();
123                         return v;
124                     }
125                     catch (Exception e)
126                     {
127                         throw new Exception(e.Message + sql, e);
128                     }
129                 }
130             }
131         }
132         #endregion
133 
134         #region ExecuteReader
135         /// <summary>
136         /// 执行sql语句
137         /// </summary>
138         /// <param name="sql"></param>
139         /// <param name="param">参数组</param>
140         /// <returns>返回DataReader对象</returns>
141         public  IDataReader ExecuteReader(string sql, IDataParameter[] param)
142         {
143             SqlConnection conn = new SqlConnection(connstr);
144             using (SqlCommand cmd = new SqlCommand(sql, conn))
145             {
146                 try
147                 {
148                     conn.Open();
149                     AttachParameters(cmd, param);
150                     IDataReader r = cmd.ExecuteReader(CommandBehavior.CloseConnection);
151                     cmd.Parameters.Clear();
152                     return r;
153                 }
154                 catch (Exception e)
155                 {
156                     throw new Exception(e.Message + sql, e);
157                 }
158             }
159         }
160         #endregion
161 
162         #region ExecuteDataSet
163         /// <summary>
164         /// 执行sql语句
165         /// </summary>
166         /// <param name="sql"></param>
167         /// <param name="param">参数组</param>
168         /// <returns>返回DataSet对象</returns>
169         public  DataSet ExecuteDataSet(string sql, IDataParameter[] param)
170         {
171             using (SqlConnection conn = new SqlConnection(connstr))
172             {
173                 using (SqlCommand cmd = new SqlCommand(sql, conn))
174                 {
175                     conn.Open();
176                     AttachParameters(cmd, param);
177                     using (SqlDataAdapter da = new SqlDataAdapter())
178                     {
179                         da.SelectCommand = cmd;
180                         DataSet ds = new DataSet();
181                         try
182                         {
183                             ds.EnforceConstraints = false;
184                             da.Fill(ds);
185                             ds.EnforceConstraints = true;
186                             //当系统从数据库中获取数据并填充到datatable中时,或自动根据其约束来验证每一行(比如主键、唯约束等等),这样是以牺牲系统性能为代价的。
187                             //既然是从关系数据库中提取出来的数据,那么对数据约束的检查应该丢给它来做。在填充数据集前可以利用dataset的EnforceConstraints属性来开关数据约束检查。
188                         }
189                         catch (Exception e)
190                         {
191                             throw new Exception(e.Message + sql, e);
192                         }
193                         cmd.Parameters.Clear();
194                         return ds;
195                     }
196                 }
197 
198             }
199         }
200         #endregion
201         public DataTable testDataTable(string sql, IDataParameter[] param)
202         {
203             DataSet set = ExecuteDataSet(sql, param);
204             return set.Tables[0];
205         }
206         #region 为DbCommand对象附加DataParameter参数
207         /// <summary>
208         /// 为DbCommand对象附加DataParameter参数
209         /// </summary>
210         /// <param name="cmd">DbCommand对象</param>
211         /// <param name="parameters">DataParameter参数数组</param>
212         public  void AttachParameters(IDbCommand cmd, IDataParameter[] parameters)
213         {
214             if (parameters == null) return;
215             foreach (IDataParameter p in parameters)
216             {
217                 if (p != null)
218                 {
219                     if (p.Value == null)
220                     {
221                         p.Value = DBNull.Value;
222                     }
223                     cmd.Parameters.Add(p);
224                 }
225             }
226         }
227         #endregion
228 
229 
230         #region Parameter
231         /// <summary>
232         /// 根据占位符和值创建参数
233         /// </summary>
234         /// <param name="name">占位符名称</param>
235         /// <param name="value">占位符的值</param>
236         /// <param name="type">数据类型</param>
237         /// <param name="size">数据最大长度</param>
238         /// <returns></returns>
239         public    IDataParameter CreateParameter(string name, object value, DbType type, int size)
240         {
241             SqlParameter p = new SqlParameter(name, type);
242             p.Value = value;
243             if (size > 0) p.Size = size;
244             return p;
245         }
246         #endregion
247 
248 
249     }
250 }

主界面将数据显示出来,目前是支持根据ID查询

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Windows.Forms;
 9 using System.Data.SqlClient;
10 using _111;
11 
12 namespace ManagerSystem
13 {
14     public partial class Main : Form
15     {
16         public Main()
17         {
18             InitializeComponent();
19         }
20 
21         private void button4_Click(object sender, EventArgs e)
22         {
23             int id;
24             Class2 ds = new Class2();
25             if (true)
26             {
27                 id = Convert.ToInt32(textBox1.Text.Trim());
28             }
29                 DataTable dt = ds.li(id);//将Id传进去得到一个数据表
30                 if (dt.Rows.Count>0)
31                 {
32                     this.textBox1.Text = dt.Rows[0]["UserId"].ToString();//显示ID
33                     this.textBox2.Text = dt.Rows[0]["UserName"].ToString();//显示用户名
34                     this.textBox4.Text = Convert.ToBoolean(dt.Rows[0]["UserSex"])?"":"";//显示性别
35                     this.textBox5.Text = dt.Rows[0]["UserPhone"].ToString();//手机号
36                     this.textBox6.Text = dt.Rows[0]["UserAge"].ToString();//年龄
37                 }
38                 else
39                 {
40                     MessageBox.Show("此ID不存在!");
41                 }
42             
43 
44 
45          
46            // this.textBox3.Text = Convert.ToString(reader["UserSex"]);//显示性别
47         }
48 
49         private void Main_Load(object sender, EventArgs e)
50         {
51 
52         }
53     }
54 }

登录成功后,显示主窗体,并且登录框消失

View Code
         static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Login login = new Login();
            if (login.ShowDialog()==DialogResult.OK)
            {
                Application.Run(new Main());
            }
            
            
        }



//Login。cs
 MessageBox.Show("登录成功");
                    this.DialogResult = DialogResult.OK;

 前面的代码没有一个中心思路下来,自己菜鸟也模模糊糊有点感觉,想着记录下来,以后回头学学,看看

//UpDate数据库  这里是UI层

View Code
 1  //更改数据
 2         private void button3_Click(object sender, EventArgs e)
 3         {
 4             //获得用户输入值
 5             int userId = TypeHelper.ToInt(textBox1.Text.Trim());
 6             string userName = textBox2.Text.Trim();
 7             string userPwd = textBox3.Text.Trim();
 8             bool userSex;
 9             string userPhone = textBox5.Text.Trim();
10             int userAge = TypeHelper.ToInt(textBox6.Text.Trim());
11 
12             if (!ValidatorHelper.IsLetter(userName) && userName != "")
13             {
14                 MessageBox.Show("用户名必须是非空英文字母");
15                 return;
16             }
17             if (userPwd == "")
18             {
19                 MessageBox.Show("密码不能为空");
20                 return;
21             }
22 
23             if (userPhone=="")
24             {
25                 MessageBox.Show("输入正确的联系方式");
26                 return;
27             }
28 
29             if (userAge > 60 || userAge < 18)
30             {
31                 MessageBox.Show("年龄在18与60之间");
32                 return;
33             }
34             if (radioButton1.Checked)
35             {
36                 userSex = true;
37             }
38             else if (radioButton2.Checked)
39             {
40                 userSex = false;
41             }
42 
43             else
44             {
45                 MessageBox.Show("输入性别");
46                 return;
47             }
48             try
49             {
50                 int phone = Convert.ToInt32(textBox5.Text.Trim());
51                 int age = Convert.ToInt32(textBox6.Text.Trim());
52 
53 
54                 UserInfo userinfo = new UserInfo();//实例化Mod
55                 //将指传给实体层
56                 userinfo.UserName = userName;
57                 userinfo.UserPassword = userPwd;
58                 userinfo.UserSex = userSex;
59                 userinfo.UserPhone = userPhone;
60                 userinfo.UserAge = userAge;
61                 userinfo.UserId = userId;
62                 SqlHelper ss = new SqlHelper();
63                 bool it = ss.update(userinfo);//这里userinfo引用的是实体类,而实体类是桥梁架通了数据层
64                 if (it)
65                 {
66                     MessageBox.Show("修改成功");
67                 }
68                 else
69                 {
70                     MessageBox.Show("修改失败");
71                 }
72             }
73             catch (Exception ex)
74             {
75                 MessageBox.Show(ex.Message);
76             }
77         }

//sqlhelper  dal层

View Code
 1  //更改数据
 2         public bool update(UserInfo userinfo)
 3         {
 4             string sql = string.Format(" UPDATE demoUsers SET UserName=@UserName,UserPassword=@UserPassword,UserSex=@UserSex,UserPhone=@UserPhone,UserAge=@UserAge WHERE UserId=@UserId");
 5             Class1 q = new Class1(cc);
 6             ArrayList paramlist = new ArrayList();
 7             paramlist.Add(q.CreateParameter("@UserName", userinfo.UserName, DbType.String, 50));
 8             paramlist.Add(q.CreateParameter("@UserPassword", userinfo.UserPassword, DbType.String, 50));
 9             paramlist.Add(q.CreateParameter("@UserSex", userinfo.UserSex, DbType.Boolean, 1));
10             paramlist.Add(q.CreateParameter("@UserPhone", userinfo.UserPhone, DbType.Int32, 4));
11             paramlist.Add(q.CreateParameter("@UserAge", userinfo.UserAge, DbType.Int32, 4));
12             paramlist.Add(q.CreateParameter("@UserId", userinfo.UserId, DbType.Int32, 4));
13             IDataParameter[] param = (IDataParameter[])paramlist.ToArray(typeof(IDataParameter));
14             object dt = q.ExecuteNonQuery(sql, param);
15             int it = Convert.ToInt32(dt);
16             return it > 0;
17             
18         }

//MOD  实体层

View Code
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace _111
 7 {
 8     public class UserInfo
 9     {
10         private string userName;
11         private string userPassword;
12         public string UserName
13         {
14             get { return userName; }
15             set { userName = value; }
16         }
17 
18         public string UserPassword
19         {
20             get { return userPassword; }
21             set { userPassword = value; }
22         }
23         private bool userSex;
24         public bool UserSex
25         {
26             get { return userSex; }
27             set { userSex = value; }
28         }
29         private string userPhone;
30         public string UserPhone
31         {
32             get { return userPhone; }
33             set { userPhone = value; }
34         }
35         private int userAge;
36         public int UserAge
37         {
38             get { return userAge; }
39             set { userAge = value; }
40         }
41         private int userId;
42         public int UserId
43         {
44             get { return userId; }
45             set { userId = value; }
46         }
47     }
48 }
原文地址:https://www.cnblogs.com/bkycjj/p/2985240.html