说明 :通过连接字符串判断用户名和密码是否一致,主要想使用配置文件解决数据库连接问题
1 先建UI界面
2 代码
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 UserLogin { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnLogin_Click(object sender, EventArgs e) { //01 先判断用户 和密码是否为空 string userName = txtUserName.Text.Trim(); string pwd = txtPwd.Text.Trim(); if (String.IsNullOrEmpty(userName)||string.IsNullOrEmpty(pwd)) { MessageBox.Show("用户名和密码不能为空!"); return; } //01创建连接字符串 string connstr = "server=.;uid=sa;pwd=sa;database=DemoDB;"; SqlConnection conn = new SqlConnection(connstr); using (conn) { using (SqlCommand cmd = new SqlCommand()) { cmd.Connection = conn; conn.Open(); //创建SQL脚本 string SqlSelect = string.Format("select * from UserInfo where EmpId = {0} and Pwd='{1}'", userName,pwd); cmd.CommandText = SqlSelect; object datared= cmd.ExecuteScalar(); if (datared != null) { MessageBox.Show("登录成功"); } else { MessageBox.Show("用户名和密码有误"); } } } } } }
3 运行效果
4 修改连接字符串,这里具体的实例不在举了,假如有多处连接数据库,每次都需要写连接字符串.而且修改起来也比较麻烦
方法一 我们可以把连接字符串封装起来,实现代码的复用性
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace UserLogin { public class DBConnectionString { public static string GetConnectionString() { return "server=.;uid=sa;pwd=sa;database=DemoDB;"; } } }
修改form1中代码,以及以后所有的类中都可以调用此方法
//01创建连接字符串
string connstr = DBConnectionString.GetConnectionString();
5 其实这种方法也存在诸多不宜,目前最常用的还是通过配置文件
5.1 修改配置文件,添加<connectionStrings>节点
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="connStr" connectionString="Data Source=127.0.0.1;uid=sa;pwd=sa;Initial Catalog=DemoDB;"/> </connectionStrings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" /> </startup> </configuration>
5.2 添加System.Configuration引用(Asp.net会自动添加)
5.3 修改代码->使用ConfigurationManager获取链接字符串。
//01创建连接字符串
string connstr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;