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里新建查询,有问题的话会有提示的。