把连接连接数据库封装

vs如果每个页面都写连接字符串去连接就很麻烦,可以封住

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace his
{
    class Dao
    {
        SqlConnection sc;
        public SqlConnection connect()
        {
            string str = @"Data Source=LAPTOP-9KFMSCG6\SQLEXPRESS;Initial Catalog=医院挂号系统-2;Integrated Security=True";
            sc = new SqlConnection(str);
            sc.Open();
            Console.WriteLine("连接成功");
            return sc;

        }
        public SqlCommand command(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, connect());
            return cmd;
        }
        public int Execute(string sql)
        {
            return command(sql).ExecuteNonQuery();
        }
        public SqlDataReader read(string sql)
        {
            return command(sql).ExecuteReader();
        }
        public void DaoClose()
        {
            sc.Close();
        }
    }
}

这样在每个页面引入就可以使用了,比如这个

public void patient()
        {         
            Dao dao = new Dao();
            //string sql = "select * from  swift_register";
            //string sql =$"select patient_name,patient_age,patient_gender from  [his].[dbo].[info_patient] where patient_id='{label7.Text}'";
            string sql = $"select patient_name,patient_age,patient_gender from info_patient where patient_id='{label7.Text}'";
            IDataReader dc = dao.read(sql);
            while (dc.Read())
            {
                label4.Text = "姓名:"+ dc["patient_name"].ToString().Trim();
                label5.Text = "性别:" + dc["patient_gender"].ToString().Trim();
                label6.Text = "年龄:" + dc["patient_age"].ToString().Trim();
            }
            dc.Close();
            dao.DaoClose();
        }

通过下面这个语句,可以知道查询返回了多少行

int i=0;
while(dc.read()){
i+=1;
}

这个sql语句前的$有大用处

小tips:如果在C# 写的查询语句有问题的话,可以在数据库sql server里新建查询,有问题的话会有提示的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值