【C#】使用C#连接SQLServer数据库,完成简单的查询功能
创建这几个包,将项目分成三层架构,直接在Default.aspx编写UI层即可。这里创建了两种表,分别是 stu_user 和 user_department。最后再给数据库添加几条数据,数据库这部分就完成了。本次使用的是web项目,选择以下内容即可。可以通过姓名和部门进行用户信息的查询。
使用C#连接SQLServer数据库,完成简单的查询功能
SQL Server创建数据库表
创建数据库:
创建表:
这里创建了两种表,分别是 stu_user 和 user_department
最后再给数据库添加几条数据,数据库这部分就完成了。
创建 ASP.NET web项目
本次使用的是web项目,选择以下内容即可。
创建这几个包,将项目分成三层架构,直接在Default.aspx编写UI层即可。
代码示例
UI(aspx):
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="demo111._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="姓名:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Height="22px" Width="89px"></asp:TextBox>
<asp:Label ID="Label2" runat="server" Text="部门:"></asp:Label>
<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="查询" onclick="Button1_Click"
Height="27px" Width="45px" />
<asp:GridView ID="GridView1" runat="server" Width="245px"
AutoGenerateColumns="False" Height="209px">
<Columns>
<asp:BoundField HeaderText="编号" DataField="id" />
<asp:BoundField DataField="name" HeaderText="姓名" />
<asp:BoundField DataField="age" HeaderText="年龄" />
<asp:BoundField DataField="sex" HeaderText="性别" />
<asp:BoundField DataField="departmentName" HeaderText="部门" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
UI(aspx.cs)
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using Model;
using BLL;
namespace demo111
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<User> users = new List<User>();
QueryStudentBLL qsBLL = new QueryStudentBLL();
users = qsBLL.QueryUser();
GridView1.DataSource = users;
GridView1.DataBind();
//第一次加载页面时才执行
if (!IsPostBack)
{
DropDownList1.Items.Insert(0, "请选择");
List<Department> departments = qsBLL.getDepartment();
foreach (Department de in departments)
{
DropDownList1.Items.Add(new ListItem(de.departmentName, de.id + ""));
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = null;
List<User> users = new List<User>();
QueryStudentBLL qsBLL = new QueryStudentBLL();
string name = TextBox1.Text;
string departmentName = DropDownList1.SelectedItem.ToString();
users = qsBLL.QueryUserByName(name, departmentName);
GridView1.DataSource = users;
GridView1.DataBind();
}
}
}
Model:
User:
namespace Model
{
public class User
{
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
public int departmentId { get; set; }
//Department中的departmentName
public string departmentName { get; set; }
}
}
Department:
namespace Model
{
public class Department
{
public int id { get; set; }
public string departmentName { get; set; }
}
}
DAL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Model;
namespace DAL
{
public class QueryStudentDAL
{
//查询所有User和对应的部门
public List<User> QueryUser()
{
string sql = "select u.id, u.name, u.age, u.sex, d.departmentName from stu_user as u left join user_department as d on u.departmentId = d.id";
DataTable dt = Query(sql);
List<User> users = new List<User>();
foreach (DataRow row in dt.Rows)
{
User user = new User()
{
id = Convert.ToInt32(row["id"]),
name = row["name"].ToString(),
age = Convert.ToInt32(row["age"]),
//sex = row["sex"].ToString(),
departmentName = row["departmentName"].ToString()
};
if (Convert.ToInt32(row["sex"]) == 0)
{
string stu_sex = "女";
user.sex = stu_sex;
}
else
{
string stu_sex = "男";
user.sex = stu_sex;
}
users.Add(user);
}
return users;
}
//通过用户名和部门名查询用户信息
public List<User> QueryUserByName(string name, string departmentName)
{
string sqlone = "select u.id, u.name, u.age, u.sex, d.departmentName from stu_user as u left join user_department as d on u.departmentId = d.id ";
string sql = "";
//根据条件选择的情况写sql
if ("请选择".Equals(departmentName))
{
if (!string.IsNullOrEmpty(name))
{
sql = sqlone + "where u.name = '" + name + "';";
}
else
{
sql = sqlone;
}
}
else
{
if (!string.IsNullOrEmpty(name))
{
sql = sqlone + "where u.name = '" + name + "' and d.departmentName = '" + departmentName + "';";
}
else
{
sql = sqlone + "where d.departmentName = '" + departmentName + "';";
}
}
DataTable dt = Query(sql);
List<User> users = new List<User>();
foreach (DataRow row in dt.Rows)
{
User user = new User()
{
id = Convert.ToInt32(row["id"]),
name = row["name"].ToString(),
age = Convert.ToInt32(row["age"]),
departmentName = row["departmentName"].ToString()
};
if (Convert.ToInt32(row["sex"]) == 0)
{
string stu_sex = "女";
user.sex = stu_sex;
}
else
{
string stu_sex = "男";
user.sex = stu_sex;
}
users.Add(user);
}
return users;
}
public List<Department> getDepartment()
{
string sql = "select * from user_department;";
DataTable dt = Query(sql);
List<Department> departments = new List<Department>();
foreach (DataRow row in dt.Rows)
{
Department department = new Department() { id = Convert.ToInt32(row["id"]), departmentName = row["departmentName"].ToString() };
departments.Add(department);
}
return departments;
}
//通用查询方法
public DataTable Query(string sql)
{
SqlConnection con = new SqlConnection("Server = localhost; Database = student; uid = sa; pwd = abc123456; Trusted_Connection = False;");
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
DataTable dt = null;
if (null != ds && ds.Tables.Count > 0) dt = ds.Tables[0];
return dt;
}
}
}
BLL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using Model;
namespace BLL
{
public class QueryStudentBLL
{
//查询User和部门信息
public List<User> QueryUser()
{
QueryStudentDAL qs = new QueryStudentDAL();
List<User> users = qs.QueryUser();
return users;
}
//通过姓名和部门名查询User和部门信息
public List<User> QueryUserByName(string name, string departmentName)
{
QueryStudentDAL qs = new QueryStudentDAL();
List<User> users = qs.QueryUserByName(name, departmentName);
return users;
}
//获取部门列表
public List<Department> getDepartment()
{
QueryStudentDAL qs = new QueryStudentDAL();
List<Department> departments = qs.getDepartment();
return departments;
}
}
}
在UI层中工具箱的使用
Label
Label是一个文本框。将工具箱中的 Label 控件直接拖入到 UI 层中,在属性中可以修改该控件的信息,Text 为文本的名称,Id 用于后面通过代码操作该控件。
也可以动态操作控件名称
TextBox
TextBox是一个输入框。他在小项目中主要的用法就是在按钮方法中获取到输入框的值。
DropDownList
下拉框,可以在编辑项中自定义固定的下拉框值
也可以通过代码的形式绑定值,有两种添加的方法,第一种是 Add 方法,是直接添加,第二种是 Insert 方法,可以指定在下拉框的位置。
Button
按钮控件,修改按钮名称
在设计页中双击按钮,会自动生成一个按钮方法,点击按钮,会自动执行按钮方法。
GridView
表格控件,可以自定义添加列
在代码中,通过 ID.DataSource 设置数据来源,通过 ID.DataBind 完成数据绑定。
结果示例
可以通过姓名和部门进行用户信息的查询。

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐
所有评论(0)