上篇ADO.Net里边最后介绍了一下字符串拼接的登录方式,现在将几种登陆方式做一下详细的介绍。
1.字符串拼接的登录方式
1 static void Main(string[] args) 2 { 3 4 string dataDir = AppDomain.CurrentDomain.BaseDirectory; 5 if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) 6 { 7 dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; 8 AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); 9 }10 Console.WriteLine("请输入你的用户名");11 string username = Console.ReadLine();12 Console.WriteLine("请输入你的密码");13 string password = Console.ReadLine();14 using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;attachDBFilename=|DataDirectory|\database1.mdf;Integrated Security=true;User Instance=True"))15 {16 conn.Open();//打开数据库连接17 using (SqlCommand cmd = conn.CreateCommand())18 {19 20 // cmd.CommandText = "select count(*) from T_Login where username='" + username + "' and password='" + password + "'";//字符串拼接的方法很容易出现漏洞,什么时候都不要用字符串拼接的方式,要用参数化查询的方法,如下:21 cmd.CommandText = "select count(*) from T_Login where username=@UserName and password=@password ";////这种方法相当于直接把用户的输入和数据库里边的内容进行比较,而不是字符串的拼接,这样不容易出现漏洞22 cmd.Parameters.Add(new SqlParameter("UserName",username));23 cmd.Parameters.Add(new SqlParameter("password",password));24 int i = (int)cmd.ExecuteScalar();//返回查询结果中的第一行第一列,返回类型是objec,并将其转化成int类型25 if (i > 0)26 {27 //如果i>0,则说明在数据中有数据28 Console.WriteLine("登陆成功");29 }30 else31 {32 Console.WriteLine("登录失败");33 }34 }35 }36 }
SqlCommand的ExecuteScalar方法用于执行查询,并返回查询所返回的结果集中的第一行第一列,因为不能确定返回值的类型,所以返回值是object类型。得到自动增长字段的主键值,在values关键词前加上output inserted.id,其中id为主键字段名。执行结果就是插入的主键值,用ExecuteScalar执行最方便。
1 cmd.CommandText = "insert into T_Person(name,sex) output inserted.id values('佳佳','女')";2 int id = Convert.ToInt32(cmd.ExecuteScalar());
2.第二种用ExecuteReader()写的.
1 static void Main(string[] args) 2 { 3 4 string dataDir = AppDomain.CurrentDomain.BaseDirectory; 5 if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) 6 { 7 dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; 8 AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); 9 }10 Console.WriteLine("请输入你的用户名");11 string username = Console.ReadLine();12 Console.WriteLine("请输入你的密码");13 string password = Console.ReadLine();14 using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;attachDBFilename=|DataDirectory|\database1.mdf;Integrated Security=true;User Instance=True"))15 {16 conn.Open();//打开数据库连接17 using (SqlCommand cmd = conn.CreateCommand())18 {19 cmd.CommandText = "select * from T_Login where username=@UserName";20 cmd.Parameters.Add(new SqlParameter("UserName",username));21 using (SqlDataReader reader = cmd.ExecuteReader())22 {23 if (reader.Read())24 {25 //如果在数据中能找到数据26 string dbPassword = reader.GetString(reader.GetOrdinal("password"));//取出该数据对应的密码27 if (password == dbPassword)28 {29 Console.WriteLine("登陆成功");30 }31 else32 {33 Console.WriteLine("登录失败");34 }35 }36 else37 {38 Console.WriteLine("用户名不存在!");39 }40 41 }42 }43 }44 Console.ReadKey();45 }
执行有多行结果集的用ExecuteReader方法;reader的GetString、GetInt32等方法只接受证书参数,也就是序号,用GetOrdinal方法根据列名动态的得到序号。
用DataSet做的登陆小程序:
1 private void btnLogin_Click(object sender, EventArgs e) 2 { 3 DataTable tb = SQLHepler.ExecuteDataSet("select * from T_Persons where username=@username",new SqlParameter("username",txtUsename.Text)); 4 if (tb.Rows.Count <= 0) 5 { 6 MessageBox.Show("用户名不存在"); 7 return; 8 9 }10 //用户名存在11 DataRow row=tb.Rows[0];//取出满足用户名的那条数据12 int errortime = Convert.ToInt32(row["errortime"]);13 if (errortime >= 3)14 {15 MessageBox.Show("登陆错误次数过多,禁止登陆");16 return;17 }18 //登陆错误次数没有超过三次19 string dbPassword = Convert.ToString(row["password"]);//取出数据库中与用户名对应的密码20 if (txtPassword.Text == dbPassword)//数据库中的密码与用户输入的密码一致21 {22 SQLHepler.ExecuteNonQuery("update T_Persons set errortime=0 where username=@username",new SqlParameter("username",txtUsename.Text));23 MessageBox.Show("登陆成功!!");24 }25 else26 {27 SQLHepler.ExecuteNonQuery("update T_Persons set errortime=errortime+1 where username=@username", new SqlParameter("username", txtUsename.Text));28 MessageBox.Show("登录失败");29 }30 }
3.数据的导入,做一个简单的导入,把文件的内容导入到数据中。
1 private void button1_Click(object sender, EventArgs e) 2 { 3 //数据的导入 4 OpenFileDialog import = new OpenFileDialog(); 5 if (import.ShowDialog() != DialogResult.OK) 6 { 7 //如果对话框没有打开成功 8 return; 9 }10 11 using (FileStream fileStream = File.OpenRead(import.FileName))12 {13 using (StreamReader reader = new StreamReader(fileStream, Encoding.Default))14 {15 using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;AttachDbFilename=|DataDirectory|\myDB.mdf;Integrated Security=True;User Instance=True;"))16 { //创建数据库连接时很耗时的,因此不要每次操作都创建连接17 conn.Open();18 //清除数据库中原有的数据19 using (SqlCommand cmd1 = conn.CreateCommand())20 {21 cmd1.CommandText = "delete from T_Mark";22 cmd1.ExecuteNonQuery();23 }24 using (SqlCommand cmd = conn.CreateCommand())25 {26 cmd.CommandText = "insert into T_Mark values(@username,@mark) ";27 string line = "";28 while ((line = reader.ReadLine()) != null)//有数据29 {30 string[] str = line.Split('|');31 string name = str[0];32 int mark = Convert.ToInt32(str[1]);33 cmd.Parameters.Clear();//参数不能重复添加,在while中一直用的就是一个SqlCommand对象34 cmd.Parameters.Add(new SqlParameter("mark", mark));35 cmd.Parameters.Add(new SqlParameter("username",name));36 cmd.ExecuteNonQuery();37 38 }39 }40 }41 }
4.数据的导出
1 private void button2_Click(object sender, EventArgs e) 2 { //数据的导出 3 OpenFileDialog import = new OpenFileDialog(); 4 if (import.ShowDialog() != DialogResult.OK) 5 { 6 //如果对话框没有打开成功 7 return; 8 } 9 using (FileStream fileStream = File.OpenWrite(import.FileName))10 {11 using (StreamWriter writer = new StreamWriter(fileStream))12 {13 using (SqlConnection conn = new SqlConnection(@"Data Source=.\sqlexpress;AttachDbFilename=|DataDirectory|\myDB.mdf;Integrated Security=True;User Instance=True;"))14 { //创建数据库连接时很耗时的,因此不要每次操作都创建连接15 conn.Open();16 using (SqlCommand cmd = conn.CreateCommand())17 {18 string line = null;19 cmd.CommandText = "select usename, mark from T_Mark ";20 using (SqlDataReader reader = cmd.ExecuteReader())21 {22 while (reader.Read())23 {24 string name = reader.GetString(reader.GetOrdinal("usename"));25 int mark = reader.GetInt32(reader.GetOrdinal("mark"));26 line = name + "|" + mark;27 writer.WriteLine(line);28 line = "";29 }30 }31 }32 }33 34 }35 }36 MessageBox.Show("导出成功!!");37 }