1.点击工具连接数据库(此数据库必须要打开)
2.写对服务器名称跟表,身份验证自己决定
连接成功的样子
3.打开winform窗体,创建登录页面
4.在项目中引用数据库相关的命名空间
5.创建一个dao类
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace StApp
{
class Dao
{
public static SqlConnection camcon()
{
return new SqlConnection(
"Data Source=c;Initial Catalog=student;Integrated Security=True");
}
}
}
6.引用TabIndex
private void Form1_Load(object sender, EventArgs e)
{
textBox1.TabIndex = 0;
textBox1.Focus();
}
7.在登录按钮写入代码
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("请输入用户名", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
if (textBox2.Text == "")
{
MessageBox.Show("请输入密码", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
SqlConnection conn = Dao.camcon();
conn.Open();
SqlCommand cmd = new SqlCommand("select * from student where name='" + textBox1.Text + "'and pwd='" + textBox2.Text + "'", conn);
int num = Convert.ToInt32(cmd.ExecuteScalar());
if (num > 0)
{
conn.Close();
MessageBox.Show("登录成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("用户名或密码错误", "警告", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
8.展示效果
登录账号密码要跟数据库相同,不同会显示 用户名或密码错误
也可以试试这种做法(我没做过)
- 首先在Visual Studio中打开你的WinForm项目。
- 在解决方案资源管理器中右键单击你的项目,选择“添加”->“新建项”。
- 在“添加新建项”对话框中选择“数据”类别,然后选择“数据集”模板,给数据集命名,然后单击“添加”按钮。
- 在“添加新建项”对话框中选择“数据”类别,然后选择“连接字符串”模板,给连接字符串命名,然后单击“添加”按钮。
- 在“添加连接字符串”对话框中,选择你的数据库类型,输入数据库服务器名称和数据库名称,选择验证方式(Windows验证或SQL Server验证),输入用户名和密码(如果使用SQL Server验证),单击“测试连接”按钮,确保连接信息正确,然后单击“确定”按钮。
- 然后在你的WinForm中使用SqlConnection类或其他数据访问类连接并访问你的数据库。
例如,使用SqlConnection类连接数据库的代码如下:
string connectionString = "你的连接字符串";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 在这里执行数据库操作
}
还有这种方法: