现实中很多项目中页面都会有复杂的操作,增删改、分页已经很普遍了。还有数据验证、编辑指定列等功能。
现把所有功能都写在一个页面中,方便需要的朋友参考。
示例用到的相关组件:
Extjs版本:3.2.1
Newtonsoft.Json.dll (把数据序列化为Json格式)文件可在Newtonsoft官网去下载http://james.newtonking.com/
AjaxPro.2.dll (直接与页面后台通过Ajax方式交互)官网地址:http://ajaxpro.codeplex.com
Oracle.DataAccess.dll 由Oracle安装文件中获取,提供对Oracle数据库的操作相关。示例使用Oracle10g,文件路径F:/oracle/product/10.2.0/db_1/BIN 可根据自己安装目录寻取
1、Oracle数据库表:
create table MacInfo (
MacInfo_ID varchar2(17) primary key,
Com_ID int null,
ComUser_ID int null,
Mac_Address varchar2(17) not null,
Mac_ApplyIP int null,
Mac_Status int null,
Mac_UserName nvarchar2(50) null,
Mac_Remark nvarchar2(200) null
)
2、项目相关配置:
I、添加对Oracle.DataAccess.dll、AjaxPro.2.dll、Newtonsoft.Json.dll的引用
II、在Web.config中添加如下配置
<configuration>
<location path="ajaxpro">
<system.web>
<httpHandlers>
<add verb="GET,POST" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
</httpHandlers>
</system.web>
</location>
</configuration>
3、页面关键代码:
说明:页面使用到了ProgressBarPager.js(滚动条式分页)和RowEditor.js(行内编辑)文件
RowEditor.js文件做了点修改。代码如下:
onRowClick: function(g, rowIndex, e){
if(state=='add'){}else{
if(this.clicksToEdit == 'auto'){
var li = this.lastClickIndex;
this.lastClickIndex = rowIndex;
if(li != rowIndex && !this.isVisible()){
return;
}
}
this.startEditing(rowIndex, false);
this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
}
},
onRowDblClick: function(g, rowIndex, e){
if(state=='add'){}else{
this.startEditing(rowIndex, false);
this.doFocus.defer(this.focusDelay, this, [e.getPoint()]);
}
},
下面是数据展示主页面代码:ExtEditPage.aspx
<head runat="server"> <title>无标题页</title> <link href="Extjs/resources/css/ext-all.css" mce_href="Extjs/resources/css/ext-all.css" rel="Stylesheet" type="text/css" /> <mce:script src="Extjs/adapter/ext/ext-base.js" mce_src="Extjs/adapter/ext/ext-base.js" type="text/javascript"></mce:script> <mce:script src="Extjs/ext-all-debug.js" mce_src="Extjs/ext-all-debug.js" type="text/javascript"></mce:script> <mce:script src="Extjs/ux/ProgressBarPager.js" mce_src="Extjs/ux/ProgressBarPager.js" type="text/javascript"></mce:script> <link rel="stylesheet" type="text/css" href="Extjs/css/RowEditor.css" mce_href="Extjs/css/RowEditor.css" /> <mce:script src="Extjs/ux/RowEditor.js" mce_src="Extjs/ux/RowEditor.js" type="text/javascript"></mce:script> </head> <body> <form id="form1" runat="server"> <div> <mce:script type="text/javascript"><!-- var state = '';//标记是否正在添加数据 Ext.onReady(function(){ function ResumeError() { return true; } //window.onerror = ResumeError; function IPLong2Str(ipLong){ return ( (ipLong>>24) & 0xff ) + '.' +( (ipLong>>16) & 0xff ) + '.' +( (ipLong>>8) & 0xff ) + '.' +( ipLong & 0xff ); } function IPStr2Long(ipStr){ var aIPsec=ipStr.split("."); for(var i=0;i<4;i++){ if(parseInt(aIPsec[i])<16){ aIPsec[i]="0"+parseInt(aIPsec[i]).toString(16); }else{ aIPsec[i]=parseInt(aIPsec[i]).toString(16); } } return parseInt("0x"+aIPsec[0]+aIPsec[1]+aIPsec[2]+aIPsec[3]); } Ext.QuickTips.init(); function showStatus(value,p,r){ if(value=="-1") return "<span style="color:red;" mce_style="color:red;">未审批</span>"; else if(value=="0") return "<span style="color:blue;" mce_style="color:blue;">已拒绝</span>"; else return "已通过"; } function showUrl(value,p,r){ return String.format('<a href="http://www.google.com.hk?id={0}" mce_href="http://www.google.com.hk?id={0}" target="_blank" >{1}</a>',r.data.ComUser_ID,value);//r.data["ComUser_ID"]也可以 } function showIP(v,p,r){ //return ExtEditPage.ParseIPAddressToStr(v).value; return IPLong2Str(v); } // create the Data Store var macInfo = Ext.data.Record.create([{ name: 'MacInfo_ID', type: 'string' }, { name: 'Com_ID', type: 'int' }, { name: 'Mac_UserName', type: 'string' },{ name: 'Mac_Address', type: 'string' },{ name: 'Mac_Status', type: 'int' },{ name: 'ComUser_ID', type: 'int' },{ name: 'Mac_ApplyIP', type: 'int' },{ name: 'Mac_Remark', type: 'string' }]); var store = new Ext.data.GroupingStore({ proxy: new Ext.data.HttpProxy({ url: 'TempPage.aspx' }), reader: new Ext.data.JsonReader({ totalProperty: "totalCount", root: "topics", fields: macInfo }), listeners: { 'update': function(thiz, record, operation){ //捕捉记录发生更改的事件 // var mac = thiz.getAt(thiz.indexOf(record)).data; //获得当前修改后的第一条记录 // if(operation == Ext.data.Record.EDIT){ //判断update时间的操作类型是否为 edit 该事件还有其他操作类型比如 commit,reject // var result = ExtEditPage.Update(mac.MacInfo_ID,mac.Mac_Address,mac.Mac_Status).value; // if(result==1){ // thiz.commitChanges(); //如果请求成功则更新本地记录 // }else{ // Ext.Msg.alert('错误','修改失败!'); // thiz.rejectChanges(); //请求失败,回滚本地记录 // } // } }, 'remove': function(thiz,record,index){ if(record.data.MacInfo_ID=='SytemDefault'){}else{ var result = ExtEditPage.Del(record.data.MacInfo_ID).value; if(result==1){ thiz.commitChanges(); //如果请求成功则更新本地记录 Ext.Msg.alert("提示","删除成功!"); }else{ Ext.Msg.alert('错误','删除失败!'); store.insert(0,record); } } } } }); store.load({params:{start:0, limit:10}}); var fm = Ext.form; //var ideditor=new fm.TextField({ allowBlank: false }); var editor = new Ext.ux.grid.RowEditor({ saveText: '保存', cancelText: '取消', errorText: '错误:', listeners: { beforeedit:function(rowedit,index){ //var rec=store.getAt(index); // if(rec.data.MacInfo_ID){//检查MacInfo_ID是否有值在是否需要编辑状态未知情况下使用 // ideditor.disable(); // } } } }); editor.on({ scope: this, afteredit: function(roweditor,change,record,index){ if(state=='add'){//新加新纪录 var value = ExtEditPage.Add(record.get('Mac_Address'),record.get('Mac_Status'),'System remark').value;//添加新纪录 if(value=="1"){ store.load({params:{start:0, limit:10}}); grid.store.reload();//添加成功,重新加载数据 state='';//还原状态 Ext.Msg.alert("提示","添加成功!"); }else{//修改记录 editor.stopEditing(); grid.store.remove(store.getAt(0)) ; grid.getView().refresh(); state='';//还原状态 Ext.Msg.alert("错误","添加失败!"); } }else{ var result = ExtEditPage.Update(record.data.MacInfo_ID,record.data.Mac_Address,record.data.Mac_Status).value; //修改 if(result==1){ grid.store.commitChanges(); Ext.Msg.alert("提示","修改成功!"); }else{ Ext.Msg.alert('错误','修改失败!'); grid.store.rejectChanges();//请求失败,回滚本地记录 } } }, canceledit: function(roweditor,change,record,index){ if(state=='add'){ grid.store.remove(store.getAt(0)); grid.getView().refresh(); state='';//更新state状态,防止其他行取消编辑误删操作 } editor.stopEditing(); } }); var grid = new Ext.grid.GridPanel({ width:820, height:320, title:'ExtJS -MacList', region: "center", store: store, margins: '0 5 5 5', loadMask: {msg:'正在加载数据...'}, plugins: [editor], view: new Ext.grid.GroupingView({ markDirty: false }), tbar: [{ iconCls: 'icon-user-add', text: '添加', handler: function(){ var e = new macInfo({ MacInfo_ID: 'SytemDefault', Com_ID: 1, Mac_UserName: 'SytemDefault', Mac_Address: '', Mac_Status: -1, ComUser_ID: 1, Mac_ApplyIP: 212121, Mac_Remark: 'SytemDefault' }); editor.stopEditing(); store.insert(0, e); grid.getView().refresh(); grid.getSelectionModel().selectRow(0); editor.startEditing(0); state='add'; } },{ ref: '../removeBtn', iconCls: 'icon-user-delete', text: '删除', disabled: true, handler: function(){ editor.stopEditing(); var s = grid.getSelectionModel().getSelections(); for(var i = 0, r; r = s[i]; i++){ store.remove(r); } grid.store.reload(); } }], // grid columns columns:[ new Ext.grid.RowNumberer(), { header: "编号", dataIndex: 'MacInfo_ID', width: 150, sortable: true, editor: { xtype: 'textfield', disabled: true } },{ header: "公司编号", dataIndex: 'Com_ID', width: 100, align: "center", sortable: true, setEditable: false, editor: { xtype: 'textfield', disabled: true } },{ header: "用户名称", dataIndex: 'Mac_UserName', width: 150, sortable: true, renderer: showUrl, editor: { xtype: 'textfield', disabled: true } },{ header: "Mac地址", dataIndex: 'Mac_Address', width: 150, align: 'center', sortable: true, editor: { xtype: 'textfield', allowBlank: false, regex: /^([0-9a-fA-F]{2})(([//s:-][0-9a-fA-F]{2}){5})$/, regexText: "Mac地址格式不对" } },{ header: "申请IP", dataIndex: 'Mac_ApplyIP', width: 140, sortable: true, renderer: showIP, editor: { xtype: 'textfield', allowBlank: false, disabled: true } },{ header: "状态", dataIndex: 'Mac_Status', width: 80, sortable: true, renderer: showStatus, editor: new fm.ComboBox({ typeAhead: true, triggerAction: 'all', // transform the data already specified in html transform: 'selState', lazyRender: true }) }], // paging bar on the bottom bbar: new Ext.PagingToolbar({ pageSize: 10, store: store, displayInfo: true, displayMsg: '共{2}条,当前为 {0} - {1} 条', emptyMsg: "No Macs to display", plugins: new Ext.ux.ProgressBarPager(), items:[ ' ', { enableToggle: true, text: '添加', toggleHandler:function(btn,pressed){ var win = new Ext.Window({ title: '新加Mac地址', width: 300, height: 200, layout: 'form', modal: true, resizable: false, items: [ { xtype: 'form', frame:true, bodyStyle:'padding:5px 5px 0', defaultType: 'textfield', labelAlign: 'left', labelWidth: 65, defaults: {allowBlank: false,width: 180}, items: [ { fieldLabel: 'Mac地址', id: 'mac_new', regex: /^([0-9a-fA-F]{2})(([//s:-][0-9a-fA-F]{2}){5})$/, regexText: "Mac地址格式不对", listeners:{ invalid: function(field,e){ Ext.getCmp("btnAdd").disable(); }, valid: function(field){ Ext.getCmp("btnAdd").enable(); } } }, new Ext.form.ComboBox({ fieldLabel: '状 态', typeAhead: true, triggerAction: 'all', mode: 'local', id: 'cboStatu', store: new Ext.data.ArrayStore({ id: 0, fields: ["sValue","sDisplay"], data: [[-1,'未审批'],[0,'已停用'],[1,'已启用']] }), valueField: 'sValue', displayField: 'sDisplay', value: '1' }), new Ext.form.TextArea({ fieldLabel: '备 注', id: 'remark', height: 50, autoScroll: true, validateOnBlur: false }) ], buttons: [{ xtype: 'button',text: '添加',id:'btnAdd',disabled: true, handler: function(){ var mac = Ext.getCmp("mac_new").getValue(); var statu = Ext.getCmp("cboStatu").getValue(); var rema=Ext.getCmp("remark").getValue(); var re = /^([0-9a-fA-F]{2})(([//s:-][0-9a-fA-F]{2}){5})$/; if(re.test(mac)){ var reValue = ExtEditPage.Add(mac,statu,rema).value; if(reValue=="1"){ store.load({params:{start:0, limit:10}}); grid.store.reload(); Ext.Msg.alert("提示","添加成功!"); }else{Ext.Msg.alert("提示","添加失败!");} win.destroy(); }else{ Ext.Msg.alert("错误","Mac格式错误!"); Ext.getCmp("mac_new").focus(true); } } }, { xtype: 'button',text: '退出', handler: function(){win.destroy();} }], buttonAlign: 'center' } ] }); win.show(); } } ] }) }); grid.render('topic-grid'); grid.getSelectionModel().on('selectionchange', function(sm){ grid.removeBtn.setDisabled(sm.getCount() < 1); }); }); // --></mce:script> <select id="selState" style="display:none" mce_style="display:none"> <option value="-1">未审批</option> <option value="1">已通过</option> <option value="0">已停用</option> </select> </div> <div id="topic-grid" style="margin:10px 0px 0px 10px" mce_style="margin:10px 0px 0px 10px" ></div> </form> </body> </html>
页面后台:ExtEditPage.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using AjaxPro; public partial class ExtEditPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e){ //如果页面有命名空间则需要写成typeof(命名空间.ExtEditPage),前台使用同样使用 命名空间.ExtEditPage AjaxPro.Utility.RegisterTypeForAjax(typeof(ExtEditPage));//注册,必须的 } [AjaxMethod] public string ParseIPAddressToStr(object gip){ int ip = Convert.ToInt32(gip); return string.Format("{3}.{2}.{1}.{0}", ip & 0xff, ip >> 8 & 0xff, ip >> 16 & 0xff, ip >> 24 & 0xff); } [AjaxMethod] public string Update(object id,object mac,object status){ MacInfo macInfo = new MacInfo(); macInfo.MacInfo_ID = id.ToString(); macInfo.Mac_Address = mac.ToString(); macInfo.Mac_Status = Convert.ToInt32(status); return DMacInfo.Update(macInfo).ToString(); } [AjaxMethod] public string Del(object id){ return DMacInfo.Delete(id.ToString()).ToString(); } [AjaxMethod] public string Add(object mac, object status,object remark){ MacInfo macinfo = new MacInfo(); macinfo.MacInfo_ID = Common.GetDateStr(DateTime.Now); macinfo.Mac_UserName = "[email protected]"; macinfo.Mac_Status = Convert.ToInt32(status); macinfo.Mac_Remark = remark.ToString(); macinfo.Mac_ApplyIP = Common.ParseIPAddress("192.168.0.130"); macinfo.Mac_Address = mac.ToString().Replace(":","-").ToUpper(); macinfo.ComUser_ID = 271; macinfo.Com_ID = 130; return DMacInfo.Add(macinfo).ToString(); } }
Common类:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; /// <summary> /// Common 的摘要说明 /// </summary> public class Common { public Common(){ } /// <summary> /// 转换日期为字符串 /// </summary> /// <param name="dt"></param> /// <returns></returns> public static string GetDateStr(DateTime dt){ StringBuilder strDate = new StringBuilder(); strDate.Append(dt.Year); strDate.Append(dt.Month < 10 ? "0" + dt.Month.ToString() : dt.Month.ToString()); strDate.Append(dt.Day < 10 ? "0" + dt.Day.ToString() : dt.Day.ToString()); strDate.Append(dt.Hour < 10 ? "0" + dt.Hour.ToString() : dt.Hour.ToString()); strDate.Append(dt.Minute < 10 ? "0" + dt.Minute.ToString() : dt.Minute.ToString()); strDate.Append(dt.Second < 10 ? "0" + dt.Second.ToString() : dt.Second.ToString()); if(dt.Millisecond < 10) strDate.Append("00").Append(dt.Millisecond); else if(dt.Millisecond < 100) strDate.Append("0").Append(dt.Millisecond); else strDate.Append(dt.Millisecond); return strDate.ToString(); } public static int ParseIPAddress(string ip){ string[] arr = ip.Split(".".ToCharArray()); if(arr == null || arr.Length != 4) { return 0; } int b = 0; int addr = 0; for(int i = 0; i < 4; i++) { b = int.Parse(arr[i]); addr |= b << ((3 - i) * 8); } return addr; } }
DMacInfo类:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Oracle.DataAccess.Client; using Oracle.DataAccess.Types; using System.Collections.Generic; using System.Text; public class DMacInfo { public DMacInfo(){} /// <summary> /// 增加一条数据 /// </summary> public static int Add(MacInfo model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into MacInfo("); strSql.Append("MacInfo_ID,Com_ID,ComUser_ID,Mac_Address,Mac_ApplyIP,Mac_Status,Mac_UserName,Mac_Remark)"); strSql.Append(" values ("); strSql.Append(":MacInfo_ID,:Com_ID,:ComUser_ID,:Mac_Address,:Mac_ApplyIP,:Mac_Status,:Mac_UserName,:Mac_Remark)"); OracleParameter[] parameters = { new OracleParameter(":MacInfo_ID", OracleDbType.Varchar2,17), new OracleParameter(":Com_ID", OracleDbType.Int32), new OracleParameter(":ComUser_ID", OracleDbType.Int32), new OracleParameter(":Mac_Address", OracleDbType.Varchar2,20), new OracleParameter(":Mac_ApplyIP", OracleDbType.Int32), new OracleParameter(":Mac_Status", OracleDbType.Int32), new OracleParameter(":Mac_UserName", OracleDbType.NVarchar2,50), new OracleParameter(":Mac_Remark", OracleDbType.NVarchar2,200)}; parameters[0].Value = model.MacInfo_ID; parameters[1].Value = model.Com_ID; parameters[2].Value = model.ComUser_ID; parameters[3].Value = model.Mac_Address; parameters[4].Value = model.Mac_ApplyIP; parameters[5].Value = model.Mac_Status; parameters[6].Value = model.Mac_UserName; parameters[7].Value = model.Mac_Remark; return DBHelper.ExecuteCommand(strSql.ToString(),CommandType.Text,parameters); } /// <summary> /// 更新一条数据 /// </summary> public static int Update(MacInfo model){ StringBuilder strSql = new StringBuilder(); strSql.Append("update MacInfo set "); strSql.Append("Mac_Address=:Mac_Address,"); strSql.Append("Mac_Status=:Mac_Status"); strSql.Append(" where MacInfo_ID=:MacInfo_ID"); OracleParameter[] parameters = { new OracleParameter(":Mac_Address", OracleDbType.Varchar2,17), new OracleParameter(":Mac_Status", OracleDbType.Int32,4), new OracleParameter(":MacInfo_ID", OracleDbType.Varchar2,17)}; parameters[0].Value = model.Mac_Address; parameters[1].Value = model.Mac_Status.ToString(); parameters[2].Value = model.MacInfo_ID; return DBHelper.ExecuteCommand(strSql.ToString(), CommandType.Text, parameters); } /// <summary> /// 删除一条数据 /// </summary> public static int Delete(string MacInfo_ID){ StringBuilder strSql = new StringBuilder(); strSql.Append("delete MacInfo "); strSql.Append(" where MacInfo_ID=:MacInfo_ID "); OracleParameter[] parameters = { new OracleParameter(":MacInfo_ID", OracleDbType.NVarchar2,17)}; parameters[0].Value = MacInfo_ID; return DBHelper.ExecuteCommand(strSql.ToString(), CommandType.Text, parameters); } /// <summary> /// 得到一个对象实体 /// </summary> public static MacInfo GetModel(string MacInfo_ID){ StringBuilder strSql = new StringBuilder(); MacInfo model = null; strSql.Append("select MacInfo_ID,Com_ID,ComUser_ID,Mac_Address,Mac_ApplyIP,Mac_Status,Mac_UserName,Mac_Remark from MacInfo "); strSql.Append(" where MacInfo_ID=:MacInfo_ID "); OracleParameter[] parameters = { new OracleParameter(":MacInfo_ID", OracleDbType.NVarchar2,17)}; parameters[0].Value = MacInfo_ID; OracleDataReader dr = DBHelper.GetDataReader(strSql.ToString(), CommandType.Text, parameters); if(dr.Read()){ model = BindReader(dr); } dr.Dispose(); dr.Close(); return model; } public static List<MacInfo> GetModelList(int dataStart, int pageSize, string strWhere, out int PageCount, out int RecordCount){ StringBuilder strSql = new StringBuilder(); strSql.Append("select * from (select a.*,Rownum rnum from (select * from macInfo order by MacInfo_ID desc) a where ROWNUM <=" + (dataStart + pageSize) + " ) where rnum > " + dataStart + ""); PageCount = 0; RecordCount = 0; List<MacInfo> arr = new List<MacInfo>(); OracleDataReader dr = DBHelper.GetDataReader(strSql.ToString(), CommandType.Text); if(dr != null){ MacInfo element; while(dr.Read()){ element = BindReader(dr); arr.Add(element); } dr.Dispose(); dr.Close(); } strSql.Remove(0, strSql.Length); //strSql.Append("select max(rnum) from (select rownum rnum from macinfo);"); strSql.Append("select count(macinfo_id) from macinfo"); object obj = DBHelper.GetScalar(strSql.ToString(), CommandType.Text); if(obj != null){ RecordCount = Convert.ToInt32(obj); PageCount = RecordCount % pageSize == 0 ? (RecordCount / pageSize) : (RecordCount / pageSize + 1); } return arr; } /// <summary> /// 绑定对象实体 /// </summary> public static MacInfo BindReader(OracleDataReader dr) { MacInfo model = null; if(dr != null){ model = new MacInfo(); if(dr["MacInfo_ID"].ToString() != ""){ model.MacInfo_ID = dr["MacInfo_ID"].ToString(); } if(dr["Com_ID"].ToString() != ""){ model.Com_ID = int.Parse(dr["Com_ID"].ToString()); } if(dr["ComUser_ID"].ToString() != ""){ model.ComUser_ID = int.Parse(dr["ComUser_ID"].ToString()); } model.Mac_Address = dr["Mac_Address"].ToString(); if(dr["Mac_ApplyIP"].ToString() != ""){ model.Mac_ApplyIP = int.Parse(dr["Mac_ApplyIP"].ToString()); } if(dr["Mac_Status"].ToString() != ""){ model.Mac_Status = int.Parse(dr["Mac_Status"].ToString()); } model.Mac_UserName = dr["Mac_UserName"].ToString(); model.Mac_Remark = dr["Mac_Remark"].ToString(); return model; }else{ return null; } } }
DBHelper类:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Transactions; using Oracle.DataAccess.Client; /// <summary> /// DBHelper 的摘要说明 /// </summary> public class DBHelper { public DBHelper(){ } //构造函数从配置文件中读取连接字符串 public static String ConnectionString = "Data Source=orcl;User ID=hr;Password=hr;"; /// <summary> /// 获取影响多少行 /// </summary> /// <param name="queryString">T-SQL语句</param> /// <param name="commandType">命令类型</param> /// <param name="param">T-SQL参数</param> /// <returns>影响多少行</returns> public static int ExecuteCommand(string queryString, CommandType commandType, params OracleParameter[] param){ int flag = 0; using(OracleConnection con = new OracleConnection(ConnectionString)){ OracleCommand command = new OracleCommand(queryString, con); command.CommandType = commandType; if(param != null){ for(int i = 0; i < param.Length; i++){ command.Parameters.Add(param[i]); } } try{ command.Connection.Open(); flag = command.ExecuteNonQuery(); }catch(Exception ex){ throw ex; }finally{ command.Connection.Close(); command.Dispose(); command = null; } } return flag; } /// <summary> /// 获取DataSet对象 /// </summary> /// <param name="queryString">T-SQL语句</param> /// <param name="commandType">命令类型</param> /// <param name="param">T-SQL参数</param> /// <returns>DataSet对象</returns> public static DataSet GetDataSet(string queryString, CommandType commandType, params OracleParameter[] param){ DataSet ds = new DataSet(); using(OracleConnection con = new OracleConnection(ConnectionString)){ OracleDataAdapter adapter = new OracleDataAdapter(queryString, con); adapter.SelectCommand.CommandType = commandType; if(param != null){ for(int i = 0; i < param.Length; i++){ adapter.SelectCommand.Parameters.Add(param[i]); } } try{ adapter.Fill(ds); }catch(Exception ex){ throw ex; }finally{ adapter.Dispose(); adapter = null; } } return ds; } /// <summary> /// 获取DataReader对象 /// </summary> /// <param name="queryString">T-SQL语句</param> /// <param name="commandType">命令类型</param> /// <param name="param">T-SQL参数</param> /// <returns>DataReader对象</returns> public static OracleDataReader GetDataReader(string queryString, CommandType commandType, params OracleParameter[] param){ OracleDataReader dataReader = null; OracleConnection con = new OracleConnection(ConnectionString); OracleCommand command = new OracleCommand(queryString, con); command.CommandType = commandType; if(param != null){ for(int i = 0; i < param.Length; i++){ command.Parameters.Add(param[i]); } } try{ command.Connection.Open(); dataReader = command.ExecuteReader(CommandBehavior.CloseConnection); }catch(Exception ex){ throw ex; } return dataReader; } /// <summary> /// 查询单个数据 /// </summary> /// <param name="queryString">T-SQL语句</param> /// <param name="commandType">命令类型</param> /// <param name="param">T-SQL参数</param> /// <returns>Object对象</returns> public static Object GetScalar(string queryString, CommandType commandType, params OracleParameter[] param){ Object obj = null; using(OracleConnection con = new OracleConnection(ConnectionString)){ OracleCommand command = new OracleCommand(queryString, con); command.CommandType = commandType; if(param != null){ for(int i = 0; i < param.Length; i++){ command.Parameters.Add(param[i]); } } try{ command.Connection.Open(); obj = command.ExecuteScalar(); }catch(Exception ex){ throw ex; }finally{ command.Connection.Close(); command.Dispose(); command = null; } } return obj; } }
Model类:
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public class MacInfo { public MacInfo(){ } #region Model private string _macinfo_id; private int _com_id; private int _comuser_id; private string _mac_address; private int _mac_applyip; private int _mac_status; private string _mac_username; private string _mac_remark; public string MacInfo_ID{ set { _macinfo_id = value; } get { return _macinfo_id; } } public int Com_ID{ set { _com_id = value; } get { return _com_id; } } public int ComUser_ID{ set { _comuser_id = value; } get { return _comuser_id; } } public string Mac_Address{ set { _mac_address = value; } get { return _mac_address; } } public int Mac_ApplyIP{ set { _mac_applyip = value; } get { return _mac_applyip; } } public int Mac_Status{ set { _mac_status = value; } get { return _mac_status; } } public string Mac_UserName{ set { _mac_username = value; } get { return _mac_username; } } public string Mac_Remark{ set { _mac_remark = value; } get { return _mac_remark; } } #endregion Model }
OK,好像代码挺多。哈哈!
整理的比较重忙,有问题的话,希望发现的朋友指出!
页面效果图: