持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第27天,点击查看活动详情
1、数据库建立
- 打开那先进的VS2017,依次点击文件、新建、项目、Visaul C#、Windows桌面、Windows窗体应用开发、确定。
- 在解决方案里面依次点击Properties、添加、新建项。
- 在右侧找到Data,然后选择基于服务的数据库,最后点击添加。
- 右键Database1.mdf打开,右键表,点击添加新表。
- 然后为新表添加几个新的字段,其中Id是默认的字段,允许NULL一栏是设置是否必填,我们是做登录系统,所以用户名和密码都是必填。此时注意把下方窗口中的Table改个名字如myTable。设置完成以后点击更新,在服务器资源管理器的空白处右键刷新即可看见我们建立完成的的表。
- 然后右键表,点击显示数据。
- 给数据库加一些数据
至此一个简易的数据库建立完成。
2、设计页面
视图中找到工具箱,在窗体加几个按钮,两个label,两个TextBox,一个button。然后把他们的文本属性改成用户名,密码,登录就好了。
3、连接数据库实现登录系统
双击button进入From1.cs开始写代码:(注意一定是双击进入)
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 shujukuf_uxi
{
public partial class Form1 : Form
{
//链接字符串
//数据库的 路径 用户名 密码 权限
string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\.NET daima\shujukuf_uxi\shujukuf_uxi\Properties\Database1.mdf;Integrated Security=True";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//获取用户信息
string name = textBox1.Text.Trim();
string psd = textBox2.Text.Trim();
//sql 字符串连接+sql语句
string sql = "select count(*) from myTable where uname='" + name + "' and password='" + psd + "'";//定义sql语句,注意双引号的使用
//string sql1 = string.Format("select count(*) from myTable where uname='{0}' and password='{ 1} '", name,psd);//第二种定义方法
//创建链接
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand(sql, con);
//打开链接
con.Open();
//MessageBox.Show("连接成功");
//执行查询
int n = Convert.ToInt32(cmd.ExecuteScalar());
if (n > 0)
{
MessageBox.Show("登陆成功");
}
else
{
MessageBox.Show("登陆失败");
}
//关闭链接
con.Close();
}
}
}
链接字符串可以在mdf文件的属性里找到。(如果路径在双引号,把双引号删掉)
4、SQL查询(补充)
打开服务器资源管理器,右键我们的表myTable点击新建查询
查询mytable
select * from myTable
5、运行
大功告成!!!