100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > c# mysql登录界面_C#窗体控件与MySQL实现登录功能

c# mysql登录界面_C#窗体控件与MySQL实现登录功能

时间:2022-05-17 07:14:52

相关推荐

c# mysql登录界面_C#窗体控件与MySQL实现登录功能

C#窗体控件与MySQL实现登录功能

1.windows窗体

控件

1 label1

2 label2

3 textBox1

4 textBox2

5 button1

6button2

代码:

using System;

using MySql.Data.MySqlClient;

using System.Windows.Forms;

namespace SQLTest

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

//点击"登录"按钮实现数据库验证登录功能

private void button1_Click(object sender, EventArgs e)

{

//1. 获取数据

//从TextBox中获取用户输入信息

string userName = this.textBox1.Text;

string userPassword = this.textBox2.Text;

//2. 验证数据

// 验证用户输入是否为空,若为空,提示用户信息

if (userName.Equals("") || userPassword.Equals(""))

{

MessageBox.Show("用户名或密码不能为空!");

}

// 若不为空,验证用户名和密码是否与数据库匹配

else

{

//用户名和密码验证正确,提示成功,并执行跳转界面。

/*数据库连接*/

//1.创建数据连接,这里注意你登录数据库的数据库名称,用户名和密码

string strcon = "server=localhost;database=c1test;uid=root;pwd=root;";

MySqlConnection con = new MySqlConnection(strcon);

try

{

//2. 打开数据库

con.Open();

//3. sql语句

string sqlSel = "select count(*) from c1test.users where username = '" + userName + "' and userpwd = '" + userPassword + "'";

MySqlCommand com = new MySqlCommand(sqlSel, con);

//4.判断executeScalar方法返回的参数是否大于0,大于0表示查找有数据

if (Convert.ToInt32(com.ExecuteScalar()) > 0)

{

MessageBox.Show("登录成功!");

//跳转主界面

this.DialogResult = DialogResult.OK;

this.Dispose();

this.Close();

}

//用户名和密码验证错误,提示错误。

else

{

MessageBox.Show("用户名或密码错误!");

}

}

catch (Exception ex)

{

MessageBox.Show(ex.Message.ToString() + "打开数据库失败");

}

}

}

}

}

数据库:

database:c1test

table:users

-- ----------------------------

-- Table structure for users

-- ----------------------------

DROP TABLE IF EXISTS `users`;

CREATE TABLE `users` (

`id` int(10) NOT NULL AUTO_INCREMENT,

`username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,

`userpwd` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,

`userid` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,

`userrole` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,

PRIMARY KEY (`id`) USING BTREE

) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;

-- ----------------------------

-- Records of users

-- ----------------------------

INSERT INTO `users` VALUES (1, 'admin', '123456', '000001', 'adminst');

INSERT INTO `users` VALUES (2, 'Eastmount', 'eastmount', '000002', 'manager');

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。