本周学习新的内容,如何连接数据库,将密码加密、新建下一个窗体以及数据窗口DataGridView的部分内容。
数据库中的参考内容:
1、代码:
连接数据库部分代码:代码中附带部分语句的解释
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LOGIN
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void labellogin_Click(object sender, EventArgs e)
{
}
private void buttonok_Click(object sender, EventArgs e)
{
string username = textBoxusername.Text.Trim(); //取出账号,Trim()用于去掉前后的空格
string password = textBoxpassword.Text.Trim(); //取出密码
//string connstr = ConfigurationManager.ConnectionStrings["connectionString"].ToString(); //读取连接字符串
string myConnString = "Data Source=.;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=123"; //连接数据库
//服务器名字:本机或其他IP地址; 数据库名称;
SqlConnection sqlconnection = new SqlConnection(myConnString); //实例化连接对象
sqlconnection.Open();
string sql = "select userid,password from login where userid='" + username + "'and password='" + password + "'"; //编写SQL命令
SqlCommand sqlCommand = new SqlCommand(sql, sqlconnection); //建立数据库于C#的联系
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); //读取数据
if (sqlDataReader.HasRows)
{
MessageBox.Show("WELCOME!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); //登录成功
labellogin.Text = "Log in:" + username;
//进入下一个窗体,将之前的窗体隐藏
Formmain formmain = new Formmain();
formmain.Show();
this.Hide();
}
else
{
MessageBox.Show("FAILED!", "notice", MessageBoxButtons.OK, MessageBoxIcon.Error); //登录失败
}
sqlconnection.Close();
}
private void buttoncancel_Click(object sender, EventArgs e)
{
Application.Exit(); //退出整个应用程序
}
}
}
下一个窗体,点击取消按钮完成操作
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace LOGIN
{
public partial class Formmain : Form
{
public Formmain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void Formmain_Load(object sender, EventArgs e)
{
// TODO: 这行代码将数据加载到表“studentDataSet.Student”中。您可以根据需要移动或删除它。
this.studentTableAdapter.Fill(this.studentDataSet.Student);
}
}
}
2、新建下一个窗体。
点击【解决方案资源管理器】,点击右键,【添加】-【窗体】。
选择【窗体】,可以在名称处修改名称,点击【添加】。即可产生新的窗体。
3、关于如何将密码加密,不显示具体的信息:
点击密码的文本框,右键点击【属性】,在属性中找出【PasswordChar】,将其修改为*或者.,就可以将密码加密。
4、数据窗口-DataGridView
将数据窗口拖拽到新建的窗体中,在窗口的右上角点击三角形,在【选择数据源】中选择【添加项目数据源】,选择【数据库】,点击【下一步】,选择【数据集】,【下一步】,【新建连接】,【服务器名】为本机.,修改【身份验证为SQL Server验证】,填写【用户名】和【密码】,在【选择或输入相应的数据库名称】处选择需要的数据库,这里选择Student数据库。点击【确定】后,在【选择数据库对象】中选择相应的表,【完成】即可建立数据窗口,运行时将Student表中的信息显示在窗体中。
5、运行测试:
正确登陆时:
错误登录时: