用C#实现用户名登录---连接数据库,查询并判断是否存在用户名
一、链接类
1.添加DBConnection类
2构造
public class DBConnection { private static string _ConnectionString = null; public static SqlConnection Connection { get { //从配置文件中读取链接字符串 _ConnectionString = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString; //使 用链接字符串构建接对象 SqlConnection conn = new SqlConnection(_ConnectionString); return conn; } } }
(也可以在get{}中定义一个string变量接收configuration)
public class DBConnection { public static SqlConnection Connection { get { //从配置文件中读取链接字符串 string _ConnectionString = ConfigurationManager.ConnectionStrings["mydb"].ConnectionString; //使 用链接字符串构建接对象 SqlConnection conn = new SqlConnection(_ConnectionString); return conn; } } }
二、添加配置文件
1.引用右键添加system.configuration引用
2.添加新建项--应用程序配置文件
3.APP.config
<connectionStrings> <add name="mydb" connectionString="server=.;database=mydb;uid=sa;pwd=123"/> </connectionStrings>
//注意:配置文件中name名要与DBConnection类中ConnectionString[""]中的字段一样
三、打开关闭数据库
1.Main函数调用DBConnection类里面的Connection属性
class Program { static void Main(string[] args) { SqlConnection conn = DBConnection.Connection; Console.WriteLine(conn.State); conn.Open(); Console.WriteLine(conn.State); conn.Close(); Console.WriteLine(conn.State); } }
执行结果
时间: 2024-10-10 15:52:43