写在前面:本人是来自一所地方性大学的大四的本科生是第一次写技术blog,之前做了一个shibai的项目自己承诺过要把代码分享出来。。现在由于某些原因已经弃用ASP.NET了,但是回想之前学习的时候发现这种有针对某个框架的开发没多少技术资源,现特奉上自己的一点点意见,希望对大家有用....加油coding(其实我发现写再多的代码也没有实际的和一个妹子相处好,为什么有这种感慨呢,最近喜欢上一个妹子了,有点感慨吧。。希望大家都能和自己喜欢的人在一起吧)
进入正题:开发工具 vs 2013+SQL server 2013
前期知识介绍
看懂本文需要有 C#基础知识 +SQL知识+Jquery+HTML +CSS+ASP.NET Web编程知识
easyui 的datagrid插件介绍:
在HTML中页面引入datagrid组件:
1)HTML的方式 :相信懂html的朋友都看的懂
<table class="easyui-datagrid">
<thead>
<tr>
<th data-options="field:'code'">Code</th>
<th data-options="field:'name'">Name</th>
<th data-options="field:'price'">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>001</td><td>name1</td><td>2323</td>
</tr>
<tr>
<td>002</td><td>name2</td><td>4612</td>
</tr>
</tbody>
</table>
2)js的方式引入easy的datagrid组件和上面的效果是一样的
先 在 html中 引入一个空table标签
<table id="dg"></table>
--js代码:
$('#dg').datagrid({
url:'datagrid_data.json',
columns:[[
{field:'code',title:'Code',width:100},
{field:'name',title:'Name',width:100},
{field:'price',title:'Price',width:100,align:'right'}
]]
});
我实现的效果和我的代码:
现在讲解怎么实现表格的加载:(上自己的代码。。。我爱你 w.x.l)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PostKq.aspx.cs" Inherits="EasyUI的例子.webcontent.PostKq" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script type="text/javascript" src="../Script/jquery-3.3.1.js"></script>
<script type="text/javascript" src="../Script/jquery-3.3.1.min.js"></script>
<link href="../easyui/themes/default/easyui.css" rel="stylesheet" />
<link href="../easyui/themes/icon.css" rel="stylesheet" />
<script type="text/javascript" src="../easyui/jquery.min.js"></script>
<script type="text/javascript" src="../easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../easyui/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
$(function () {
$('#dd').dialog('close');
$('#dg').datagrid({
url: '../webcontent/LoadClassStudentData.ashx',
singleSelect: 'true',
width:500,
columns: [[
{ field: 'sno', title: '学号', width: 100, align: 'left' },
{ field: 'class_id', title: '班级', width: 100 },
{ field: 'grade', title: '年级', width: 50, align: 'left' },
{ field: 'sname', title: '姓名', width: 60, align: 'left' },
{ field: 'levels', title: '层次', width: 50, align: 'left' },
{
field: 'xxxxx', title: '操作', width: 100, align: 'left', formatter: function (value, row, index) {
return "<a href='#' onclick='update("+index+")' >点击提交考勤</a> ";
}
}
]],
toolbar: [{
iconCls: 'icon-edit',
handler: function () { }
}, '-', {
iconCls: 'icon-help',
handler: function () { }
}],
striped: true,
// 显示分页工具栏
pagination: true,
pageList: [5, 10]
});
//提交数据
$('#btnSave').click(function () {
var week = $('#week').val();
var quekuang = $('#quekuang').val();
var late = $('#late').val();
var wdm = $('#wdm').val();
var sno = $('#sno').val();
var details = $('#details').val();
if (week.trim() == '' || quekuang.trim() == '' || late.trim() == '' || wdm.trim() == '' || sno.trim() == '' || details.trim()=='') {
$.messager.alert('来自网页的消息', '还有数据未填写完成若没有的填0或者无!', 'info');
}
else {
//do ajax
var arr = new Array();
arr[0] = sno;
arr[1] = week;
arr[2] = quekuang;
arr[3] = late;
arr[4] = wdm;
arr[5] = details;
$.ajax({
type: "post",
url: "../webcontent/PostKq.aspx/InsertKq",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ arr: arr }),//键值对
success: function (data) {
$.messager.alert('来自网页的信息', data.d, 'info');
setTimeout(function () { //使用 setTimeout()方法设定定时2000毫秒
$('#quekuang').val('');//页面刷新
quekuang = $('#quekuang').val('');
late = $('#late').val('');
wdm = $('#wdm').val('');
details = $('#details').val('');
}, 2000);
},
error: function (data) {
alert("出错了!");
}
});
}
});
});
function update(index) {
$('#dg').datagrid('selectRow', index);
var row = $('#dg').datagrid('getSelected');
var sno = row["sno"];
$('#sno').val(sno);
$('#dd').dialog('open');
}
/*
插入班级考勤信息的数据
*/
function InsertClassKQ() {
var qjtype = $('#tjtype').find('option:selected').text();//获取选中的值
if (qjtype == '请选择') {
$.messager.show({
title: '来自网页的消息',
msg: '必须选择一种提交类型!',
timeout: 3000,
showType: 'show',
style: {
right: '',
top: document.body.scrollTop + document.documentElement.scrollTop,
bottom: ''
}
});
}//end if
else if (qjtype == '晚点名') {
//晚点名数据的提交
//不管那些不关心的数据
var txtjlid = $('#txtjlid').val();
var stuSum = $('#stuSum').val();
var txtpresentnum = $('#txtpresentnum').val();
var txtwdm = $('#txtwdm').val();
var class_id = $('#txtcalss').val();
var arr = new Array();
if (stuSum.trim() == '' || txtpresentnum.trim() == '' || txtwdm.trim() == '' || class_id.trim() == '') {
$.messager.alert('来自网页的消息', '需要提交的数据没输入完!', 'info');
}
//ID, Cname, studentNum, PresentNum, quekeNum, R_DMNum, Record_Time
else {//do ajax post
arr[0] = txtjlid;
arr[1] = stuSum;
arr[2] = txtpresentnum;
arr[3] = txtwdm;
arr[4] = class_id;
$.ajax({
type: "post",
url: "../webcontent/PostKq.aspx/InsertWDM",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ arr: arr }),//键值对
success: function (data) {
$.messager.alert('来自网页的信息', data.d, 'info');
},
error: function (data) {
alert("出错了!");
}
});
}
}//end of else if
else {//提交班级旷课信息
var txtjlid = $('#txtjlid').val();
var stuSum = $('#stuSum').val();
var txtpresentnum = $('#txtpresentnum').val();
var txtqueke = $('#txtqueke').val();
var selectcourse = $('#selectcourse').find('option:selected').text();
var class_id = $('#txtcalss').val();
var arr = new Array();
if (selectcourse == '请选择') {
$.messager.alert('来自网页的消息', '必须选择一门要提交考勤的课程信息!', 'info');
}
else { //do ajax Post
arr[0] = txtjlid;
arr[1] = stuSum;
arr[2] = txtpresentnum; arr[3] = txtqueke; arr[4] = selectcourse;
arr[5] = class_id;
$.ajax({
type: "post",
url: "../webcontent/PostKq.aspx/InsertQueke",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ arr: arr }),//键值对
success: function (data) {
$.messager.alert('来自网页的信息', data.d, 'info');
},
error: function (data) {
alert("出错了!");
}
});//
}//end else
}//end outer else
}
</script>
<style type="text/css">
#tb tr td {
margin-left:20px;
padding-left:20px;
border-bottom:2px dotted red;
padding-top:15px;
}
</style>
</head>
<body>
<div class="easyui-layout" data-options="fit:true" ">
<div region="west" split="true" title="提交班级考勤" style="width:650px;">
<div class="contents">
<table id="dg" style="padding-left:20px" class="easyui-datagrid"></table>
</div>
</div>
<div id="content" region="center" title="班级明细考勤" style="padding:5px;">
<!--班级明细考勤-->
<div id="divcontent">
<p style="color:red">以下是班级课程的考勤,请认真填写 注:当提交类型为上课的时候晚点名未到人数不填,反之为晚点名时缺课人数不填 班级必填</p>
<table id="tb" style="margin-left:30px;margin-top:20px;padding:15px;">
<tr style=" border-bottom:5px dashed red;">
<td ><label>记录编号:</label>
<input type="text" class="easyui-validatebox" required="required" id="txtjlid" readonly="readonly" runat="server" />
</td>
<td class="auto-style1"><label>课程名称:</label><label><select id="selectcourse">
<option selected="selected">请选择</option>
<%
string class_id = txtcalss.Value;
string sql = "select distinct cname from Course_info where class like '"+class_id+"%'";
DataTable dt=EasyUI的例子.SqlHelp.DT(sql);
StringBuilder sb = new StringBuilder();
foreach (DataRow row in dt.Rows)
{
sb.AppendFormat("<option>{0}</option>",row[0].ToString());
}
Response.Write(sb.ToString());
%>
</select></label></td>
</tr>
<tr>
<td>
<label>请选择提交类型:</label>
<select id="tjtype" style="width: 65px">
<option selected="selected">请选择</option>
<option>晚点名</option>
<option>上课缺勤</option>
</select>
</td>
<td><label>学生总数:</label>
<input type="text" class="easyui-validatebox" required="required" id="stuSum" style="padding-left:3px;" placeholder="输入数字如40" onkeyup="this.value=this.value.replace(/\D/g,'')" />
</td>
</tr>
<tr>
<td>
<label>实到人数:</label>
<input type="text" class="easyui-validatebox" required="required" id="txtpresentnum" placeholder="输入数字如20" onkeyup="this.value=this.value.replace(/\D/g,'')" />
</td>
<td>
<label>班级:</label>
<input type="text" runat="server" class="easyui-validatebox" required="required" maxlength="11" readonly="readonly" id="txtcalss" />
</td>
</tr>
<tr>
<td>
<label>缺课人数:</label>
<input type="text" class="easyui-validatebox" required="required" maxlength="11" placeholder="输入数字如20" onkeyup="this.value=this.value.replace(/\D/g,'')" id="txtqueke" />
</td>
<td><label>晚点名未到人数:</label>
<input type="text" class="easyui-validatebox" required="required" maxlength="11" placeholder="输入数字如20" onkeyup="this.value=this.value.replace(/\D/g,'')" id="txtwdm" />
</td>
</tr>
</table>
<!--按钮区域-->
<dl>
<dd><a id="btnClassKq" href="#" onclick="InsertClassKQ()" class="easyui-linkbutton" data-options="iconCls:'icon-search'">插入该学生信息</a></dd>
</dl>
</div>
</div>
</div>
<div id="dd" class="easyui-dialog" title="提交学生考勤" style="width:500px;height:320px;padding:5px" data-options="iconCls:'icon-save',resizable:true,modal:true" >
<table>
<tr>
<td>学号:<input style="margin-left:40px;padding-left:40px;border-radius:10px;" type="text" class="easyui-validatebox" readonly="readonly" required="required" id="sno"/></td>
</tr>
<tr>
<td> 请输入周次:<input type="text" id="week" onkeyup="this.value=this.value.replace(/\D/g,'')" placeholder="如数字5" class="easyui-validatebox" style="border-radius:10px;height:20px; padding-left:30px; margin-left:5px; width: 185px;" required="required" missingMessage="周次不能为空" runat="server" /></td>
</tr>
<tr>
<td class="auto-style1">却矿次数:
<input type="text" id="quekuang" placeholder="如数字5" class="easyui-validatebox" style="border-radius:10px;height:20px;padding-left:50px; margin-left:2px;" required="required" missingMessage="请输入缺旷次数" onkeyup="this.value=this.value.replace(/\D/g,'')" runat="server" />
</td>
</tr>
<tr>
<td> 迟到次数:
<input type="text" id="late" class="easyui-validatebox" style="border-radius:10px;height:20px; margin-left:20px;padding-left:50px;" placeholder="如数字5" required="required" onkeyup="this.value=this.value.replace(/\D/g,'')" missingMessage="请输入迟到次数:" runat="server" />
</td>
</tr>
<tr>
<td> 晚点名未到次数:
<input type="text" id="wdm" class="easyui-validatebox" style="border-radius:10px;height:20px; margin-left:20px;" onkeyup="this.value=this.value.replace(/\D/g,'')" placeholder="如数字5" required="required" missingMessage="请输入晚点名未到次数:" runat="server" />
</td>
</tr>
<tr><td>
备注:
<textarea rows="5" id="details" cols="10" style="width:200px" placeholder="50字内若无备注内容请填“无”" ></textarea>
</td></tr>
</table>
<div id="dlg-buttons">
<table cellpadding="0" cellspacing="0" style="width:100%">
<tr>
<td style="text-align:right">
<a href="#" id="btnSave" class="easyui-linkbutton" runat="server" style="margin-right:20px; padding:5px;" iconCls="icon-save" >Save</a>
<a href="#" class="easyui-linkbutton" style="margin-right:20px; padding:5px;" iconCls="icon-cancel" onclick="javascript:$('#dd').dialog('close')">Close</a>
</td>
</tr>
</table>
</div>
</div>
</body>
</html>
加载表格代码讲解:
$('#dg').datagrid({
url: '../webcontent/LoadClassStudentData.ashx',
singleSelect: 'true',
width:500,
columns: [[
{ field: 'sno', title: '学号', width: 100, align: 'left' },
{ field: 'class_id', title: '班级', width: 100 },
{ field: 'grade', title: '年级', width: 50, align: 'left' },
{ field: 'sname', title: '姓名', width: 60, align: 'left' },
{ field: 'levels', title: '层次', width: 50, align: 'left' },
{
field: 'xxxxx', title: '操作', width: 100, align: 'left', formatter: function (value, row, index) {
return "<a href='#' onclick='update("+index+")' >点击提交考勤</a> ";
}
}
]],
toolbar: [{
iconCls: 'icon-edit',
handler: function () { }
}, '-', {
iconCls: 'icon-help',
handler: function () { }
}],
striped: true,
// 显示分页工具栏
pagination: true,
pageList: [5, 10]
});
//这种加载后台数据库的方式为json的数据(也就是我们常说的 类似java Map<key,value> map的方式)
//打个比方 比如本张表格的数据 后台生成json的形式 {total:{[列名:value1],[列名2:value2].....}}
// url: '../webcontent/LoadClassStudentData.ashx', 指向的是一个产生json格式的asp.net
//的一般处理程序类似于java中的servlet (注:本次采用的是webform的开发方式)
singleSelect: 'true', //定义为单选
width:500,
columns://定义列名 注意要和数据库表的列名一致 而且全部是小写不然加载不出该列
//自定义格式化列 效果是在每一行后面产生一个超连接便于操作做CUID 并注册事件 后面弹出框就是这样的原理实现的
{
field: 'xxxxx', title: '操作', width: 100, align: 'left', formatter: function (value, row, index) {
return "<a href='#' onclick='update("+index+")' >点击提交考勤</a> ";
}
后台C#代码的处理:
加载表格数据:sql server分页查询的原理读者自学结合前面json讲解中的total的讲解可以实现分页的效果
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.SessionState;
using System.Data.SqlClient;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace EasyUI的例子.webcontent
{
/// <summary>
/// LoadClassStudentData 的摘要说明
/// </summary>
public class LoadClassStudentData : IHttpHandler, IRequiresSessionState//必须继承自该接口才一般处理程序可以访问到session
{
public string classid;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user_id =context.Session["UserId"].ToString();
string clasql = "select class_id from student where sno=@sno";
SqlParameter[] para = new SqlParameter[] { new SqlParameter("@sno", SqlDbType.NVarChar) };
para[0].Value = user_id;
classid = SqlHelp.ExcuteScalar(clasql, CommandType.Text, para).ToString();
LoadStudentInfo(context,classid);
}
public List<string> list = new List<string>();
private void LoadStudentInfo( HttpContext context,string class_id)
{
string result = null;
int pageSize, pageIndex;//在页面一加载的时候肯定没有数据
pageSize = 10;
pageIndex = 1;
if (null != context.Request["rows"])
{
//获取前台传过来的每页显示数据的条数
pageSize = int.Parse(context.Request["rows"].ToString().Trim());
}
if (null != context.Request["page"])
{
//获取当前的页码
pageIndex = int.Parse(context.Request["page"].ToString().Trim());
}
PageCalc page = new PageCalc(pageIndex, pageSize);
int[] begin_end = page.start_end();
//变成分页查询
int totalrows = page.totalRows(pageSize, "select count(*) from student where class_id='"+class_id+"'");
string sql = "select sno,sname,class_id,levels,grade from(select sno,sname,class_id,levels,grade, row_number() over(order by sno) as num from student where class_id=@class_id) as t where t.num>=@start and t.num<=@end ";
SqlParameter[] par = new SqlParameter[] { new SqlParameter("@class_id", SqlDbType.NVarChar),new SqlParameter("@start",SqlDbType.Int),
new SqlParameter("@end",SqlDbType.Int)
};
par[0].Value = class_id;
par[1].Value=begin_end[0];
par[2].Value=begin_end[1];
DataTable dt = SqlHelp.DT(sql, par);
if (dt.Rows.Count > 0)
{
result = JSonHelper.CreateJsonParameters(dt, true, totalrows);
context.Response.Write(result);
}
else {
context.Response.Write("<script>alert('没有学生数据!')</script>");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
数据表转json的工具类需要自取:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Script.Serialization;
using System.Data;
public class JSonHelper
{
public static string CreateJson(DataTable table)
{
string jsname = "total";
StringBuilder json = new StringBuilder("{\""+jsname+"\":[");
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
json.Append("{");
foreach (DataColumn column in table.Columns)
{
json.Append("\""+column.ColumnName+"\":\""+row[column.ColumnName].ToString()+"\",");
}
json.Remove(json.Length - 1, 1);
json.Append("},");
}
json.Remove(json.Length - 1, 1);
}
json.Append("]}");
return json.ToString();
}
public static string CreateJsonParameters(DataTable dt, bool displayCount, int totalcount)
{
StringBuilder JsonString = new StringBuilder();
//Exception Handling
if (dt != null)
{
JsonString.Append("{ ");
if (displayCount)
{
JsonString.Append("\"total\":");
JsonString.Append(totalcount);
JsonString.Append(",");
}
JsonString.Append("\"rows\":[ ");
for (int i = 0; i < dt.Rows.Count; i++)
{
JsonString.Append("{ ");
for (int j = 0; j < dt.Columns.Count; j++)
{
if (j < dt.Columns.Count - 1)
{
//if (dt.Rows[i][j] == DBNull.Value) continue;
if (dt.Columns[j].DataType == typeof(bool))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" +
dt.Rows[i][j].ToString().ToLower() + ",");
}
else if (dt.Columns[j].DataType == typeof(string))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\",");
}
else
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\",");
}
}
else if (j == dt.Columns.Count - 1)
{
//if (dt.Rows[i][j] == DBNull.Value) continue;
if (dt.Columns[j].DataType == typeof(bool))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" +
dt.Rows[i][j].ToString().ToLower());
}
else if (dt.Columns[j].DataType == typeof(string))
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" +
dt.Rows[i][j].ToString().Replace("\"", "\\\"") + "\"");
}
else
{
JsonString.Append("\"" + dt.Columns[j].ColumnName.ToLower() + "\":" + "\"" + dt.Rows[i][j] + "\"");
}
}
}
/*end Of String*/
if (i == dt.Rows.Count - 1)
{
JsonString.Append("} ");
}
else
{
JsonString.Append("}, ");
}
}
JsonString.Append("]");
JsonString.Append("}");
return JsonString.ToString().Replace("\n", "");
}
else
{
return null;
}
}
public static string DataTableToJson(DataTable table, string name)
{
StringBuilder Json = new StringBuilder("{\""+name+"\":[");
if (table.Rows.Count > 0)
{
foreach (DataRow row in table.Rows)
{
Json.Append("{");
foreach (DataColumn cloumn in table.Columns)
{
Json.Append("\""+cloumn.ColumnName+"\":\""+row[cloumn.ColumnName].ToString()+"\",");
}
Json.Remove(Json.Length - 1, 1);
Json.Append("},");
}
Json.Remove(Json.Length - 1, 1);
}
Json.Append("]}");
return Json.ToString();
}
}
分页类:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Data;
using System.Text;
using System.Configuration;
using System.Drawing;
namespace EasyUI的例子
{
public class PageCalc
{
public int pageIndex;
public int pagesize;
public int PageCount(int pagesize,string sql)
{
return CalcPageCount(pagesize,sql);
}
#region 计算总的页数
private int CalcPageCount(int pagesize,string sql)
{//AreaId, AreaName, AreaPid //AreaFull
using (SqlConnection con = new SqlConnection(SqlHelp.Strconn()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = sql;
int RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
int pageSize = pagesize;
int pageCounts = Convert.ToInt32(Math.Ceiling((double)RecordCount / pageSize));
return pageCounts;
}
}
}
#region 计算总的行数
public int totalRows(int PageSize, string sql) {
using (SqlConnection con = new SqlConnection(SqlHelp.Strconn()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
object excuteScalar = cmd.ExecuteScalar();
string result= excuteScalar.ToString();
return int.Parse(result);
}
}
}
#endregion
#endregion
public PageCalc(int PagIndex,int pagesize)
{
this.pageIndex = PagIndex;
this.pagesize = pagesize;
}
#region 计算查询的起始位置
public int[] start_end()
{
int[] nums = new int[2];
nums[0] = (this.pageIndex - 1) * pagesize + 1;
nums[1] = this.pageIndex * pagesize;
return nums;
}
#endregion
}
}
数据库工具类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace EasyUI的例子
{
public class SqlHelp
{
public static string Strconn()
{
return ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
}
#region 返回受影响行数的方法
/// <summary>
/// 返回受影响行数的方法
/// </summary>
/// <param name="sql"></param>
/// <param name="command"></param>
/// <param name="par"></param>
/// <returns></returns>
public static int Excutnonquery(string sql, CommandType command, SqlParameter[] par)
{
using (SqlConnection con = new SqlConnection(SqlHelp.Strconn()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddRange(par);
return cmd.ExecuteNonQuery();
}
}
}
#endregion
#region 插入数据到数据库
/// <summary>
/// 返回影响行数3
/// </summary>
/// <param name="sql"></param>
/// <returns></returns>
public static int EXCUTEROW(string sql)
{
using (SqlConnection con = new SqlConnection(SqlHelp.Strconn()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
return cmd.ExecuteNonQuery();
}
}
}
#endregion
#region 返回一张表的方法
/// <summary>
/// 返回一张表的方法
/// </summary>
/// <param name="sql"></param>
/// <param name="par"></param>
/// <returns></returns>
public static DataTable DT(string sql)
{
using (SqlConnection conn = new SqlConnection(SqlHelp.Strconn()))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}
}
}
#endregion
#region 返回一张表的方法重载2
/// <summary>
/// 返回一张表的方法重载2
/// </summary>
/// <param name="sql"></param>
/// <param name="par"></param>
/// <returns></returns>
public static DataTable DT(string sql, SqlParameter[] para)
{
using (SqlConnection conn = new SqlConnection(SqlHelp.Strconn()))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(para);
using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}
}
}
#endregion
#region 查询学生方法
/// <summary>
/// 查询学生方法3
/// </summary>
/// <param name="sql"></param>
/// <param name="type"></param>
/// <param name="para"></param>
/// <returns></returns>
public static DataTable DT(string sql, CommandType type, SqlParameter[] para)
{
using (SqlConnection conn = new SqlConnection(SqlHelp.Strconn()))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(para);
using (SqlDataAdapter ada = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
ada.Fill(dt);
return dt;
}
}
}
}
#endregion
#region 返回查询的首行的元素
public static string ExcuteScalar(string sql, CommandType command, SqlParameter[] par)
{
using (SqlConnection con = new SqlConnection(SqlHelp.Strconn()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.AddRange(par);
return cmd.ExecuteScalar().ToString();
}
}
}
#endregion
#region 返回查询的首行首列的元素
/// <summary>
/// 返回查询的首行首列的元素,无sql参数
/// </summary>
/// <param name="sql"></param>
/// <param name="command"></param>
/// <returns></returns>
public static object ExcuteScalar(string sql, CommandType command)
{
using (SqlConnection con = new SqlConnection(SqlHelp.Strconn()))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
object excuteScalar = cmd.ExecuteScalar();
return excuteScalar;
}
}
}
#endregion
}
}