最近都在看小孔子cms的代码,其添加与修改数据十分方便,做下笔记,代码主要提取自小孔子cms,去掉了不用的函数并把相关代码写到一个文件中:
结合上面的图片,当我们要往数据库中添加数据时,代码如下:
dataHandle doh = new dataHandle();
doh.AddBind(tbxWebName, "link_webname", true);
doh.AddBind(tbxWebUrl, "link_weburl", true);
doh.AddBind(tbxLogoUrl, "link_logourl", true);
doh.AddBind(tbxOrderNum, "link_ordernum", false);
doh.AddBind(ddlStyle, "link_style", false);
doh.AddBind(rblAudit, "link_audit", false);
doh.Add();
int result = Convert.ToInt32(doh.InsertData("db_link"));
Response.Write(result.ToString());
绑定数据指的是从数据库中读取一条记录,并自动绑定到表单的控件中,代码如下(假设读取的id=8):
代码如下:
dataHandle doh = new dataHandle();
doh.AddBind(tbxWebName, "link_webname", true);
doh.AddBind(tbxWebUrl, "link_weburl", true);
doh.AddBind(tbxLogoUrl, "link_logourl", true);
doh.AddBind(tbxOrderNum, "link_ordernum", false);
doh.AddBind(ddlStyle, "link_style", false);
doh.AddBind(rblAudit, "link_audit", false);
doh.ConditionExpress = "id = 8";
doh.tableName = "db_link";
doh.BindWhenUp();
修改数据与添加数据差不多:
代码如下:
dataHandle doh = new dataHandle();
doh.ConditionExpress = "id = 8";
doh.AddBind(tbxWebName, "link_webname", true);
doh.AddBind(tbxWebUrl, "link_weburl", true);
doh.AddBind(tbxLogoUrl, "link_logourl", true);
doh.AddBind(tbxOrderNum, "link_ordernum", false);
doh.AddBind(ddlStyle, "link_style", false);
doh.AddBind(rblAudit, "link_audit", false);
doh.Add();
int result = Convert.ToInt32(doh.UpData("db_link"));
Response.Write(result);
而aspx文件详细代码: XML/HTML
网站:
<asp:TextBox ID="tbxWebName" runat="server"></asp:TextBox>
<br />
<br />
域名:<asp:TextBox ID="tbxWebUrl" runat="server"></asp:TextBox><br />
<br />
logo地址:<asp:TextBox ID="tbxLogoUrl" runat="server" Width="198px"></asp:TextBox><br />
<br />
排序:<asp:TextBox ID="tbxOrderNum" runat="server"></asp:TextBox><br />
<br />
是否审核:<asp:RadioButtonList ID="rblAudit" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">是</asp:ListItem>
<asp:ListItem Selected="True" Value="0">否</asp:ListItem>
</asp:RadioButtonList>
<br />
<br />
显示方式:
<br />
<asp:DropDownList ID="ddlStyle" runat="server">
<asp:ListItem Value="1">文字</asp:ListItem>
<asp:ListItem Value="2">图片</asp:ListItem>
<asp:ListItem Value="3">待定</asp:ListItem>
</asp:DropDownList><br />
<br />
<asp:Button ID="btnOk" runat="server" Text="提交" OnClick="btnOk_Click" /> <asp:Button
ID="btnEnter" runat="server" OnClick="btnEnter_Click" Text="绑定" />
<asp:Button ID="btnUp" runat="server" OnClick="btnUp_Click" Text="更改" /><br />
<br />
<asp:Label ID="lblResult" runat="server" Text="结果"></asp:Label></div>
我对代码做了很多注释,大家有兴趣可以看看:
代码如下:
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 System.Data.OleDb;
using System.Text;
namespace mycms.DataOper.Data
{
/// <summary>
/// dataHandle 的摘要说明
/// </summary>
public class dataHandle
{
public dataHandle()
{
this.conn = new OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;Data Source = |DataDirectory|mycms.mdb");
this.conn.Open();
this.cmd = conn.CreateCommand();
this.da = new OleDbDataAdapter();
}
#region webform
//这个用来存放包括控件类型,字段,是否是字符串
public ArrayList alBinderItems = new ArrayList(8);
//这个只用来存放字段,值
public ArrayList alFieldItems = new ArrayList(8);
/// <summary>
/// 建立文本框到数据字段的绑定
/// </summary>
public void AddBind(TextBox tbx, string field, bool isStringType)
{
alBinderItems.Add(new BinderItem(tbx, field, isStringType));
}
/// <summary>
/// 下拉列表
/// </summary>
public void AddBind(DropDownList dd, string field, bool isStringType)
{
alBinderItems.Add(new BinderItem(dd, field, isStringType));
}
public void AddBind(RadioButtonList rb, string field, bool isStringType)
{
alBinderItems.Add(new BinderItem(rb, field, isStringType));
}
/// <summary>
/// 多选框
/// </summary>
public void AddBind(CheckBoxList cb, string field, bool isStringType)
{
alBinderItems.Add(new BinderItem(cb, field, isStringType));
}
/// <summary>
/// 需要修改数据时取出数据库中的记录填充到表单中
/// </summary>
public void BindWhenUp()
{
if (alBinderItems.Count == 0)
{
return;
}
BinderItem bi;
StringBuilder sbSql = new StringBuilder("select ");
for (int i = 0; i < alBinderItems.Count; i++)
{
bi = (BinderItem)alBinderItems[i];
//防止出现变量名
sbSql.Append("[" + bi.field + "]");
sbSql.Append(",");
}
sbSql.Remove(sbSql.Length - 1,1);
sbSql.Append(" from ");
sbSql.Append(this.tableName);
sbSql.Append(" where 1 = 1 and ");
sbSql.Append(this.ConditionExpress);
this.sqlCmd = sbSql.ToString();
dt = this.GetDataTable();
//如果没有记录则抛出异常
if (dt.Rows.Count == 0)
{
throw new ArgumentException("记录不存在");
}
DataRow dr = dt.Rows[0];
for (int j = 0; j < alBinderItems.Count; j++)
{
bi = (BinderItem)alBinderItems[j];
bi.SetValue(dr[bi.field].ToString());
}
}
/// <summary>
/// 该方法实现从alBinderItems到alFieldItems的转换,目的:alFieldItems可以转为DbKeyItem,操作数据库时需要用到DbKeyItem
/// </summary>
public void Add()
{
if (this.alBinderItems.Count == 0)
{
return;
}
BinderItem bi = null;
for (int i = 0; i < alBinderItems.Count; i++)
{
bi = ((BinderItem)alBinderItems[i]);
AddFieldItem(bi.field, bi.GetValue());
}
}
/// <summary>
/// 添加一个字段/值对到数组中
/// </summary>
public void AddFieldItem(string _fieldName, object _fieldValue)
{
_fieldName = "[" + _fieldName + "]";
//遍历看是否已经存在字段名
for (int i = 0; i < this.alFieldItems.Count; i++)
{
if (((DbKeyItem)this.alFieldItems[i]).fieldName == _fieldName)
{
throw new ArgumentException("字段已经存在");
}
}
this.alFieldItems.Add(new DbKeyItem(_fieldName, _fieldValue));
}
#endregion
#region 操作数据
#region 这里声明有关数据操作的必要参数
//当前所使用的数据库连接
protected OleDbConnection conn;
//当前所使用的命令对象
protected OleDbCommand cmd = new OleDbCommand();
//当前所使用的数据库适配器
protected OleDbDataAdapter da;
//当前的SQL语句
public string sqlCmd = string.Empty;
//当前操作所涉及的数据库表名
public string tableName = string.Empty;
//SQL条件
public string ConditionExpress;
//用于存放从数据库中取得的数据记录
protected DataTable dt;
#endregion
/// <summary>
/// 根据当前alFieldItem数组中存储的字段/值向指定表中添加一条记录。返回自动增长id
/// </summary>
/// <param name="_talbeName"></param>
/// <returns></returns>
public int InsertData(string _talbeName)
{
this.tableName = _talbeName;
this.sqlCmd = "insert into " + this.tableName + "(";
string temValue = " values(";
for (int i = 0; i < this.alFieldItems.Count; i++)
{
this.sqlCmd += ((DbKeyItem)alFieldItems[i]).fieldName + ",";
temValue += "@para" + i.ToString() + ",";
}
//分别去掉,
this.sqlCmd = Input.CutComma(this.sqlCmd) + ")" + Input.CutComma(temValue) + ")";
//声明执行语句
this.cmd.CommandText = this.sqlCmd;
GenParameters();
cmd.ExecuteNonQuery();
int autoId = 0;
try
{
cmd.CommandText = "select @@identity as id";
autoId = Convert.ToInt32(cmd.ExecuteScalar());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return autoId;
}
/// <summary>
/// 根据当前alFieldItem数组中存储的字段/值和条件表达式所指定的条件来更新数据库中的记录,返回受影响的行数
/// </summary>
/// <param name="_tableName">更新的数据表名称</param>
/// <returns>返回此次操作所影响的数据行数</returns>
public int UpData(string _tableName)
{
this.tableName = _tableName;
this.sqlCmd = "update " + this.tableName + " set ";
for (int i = 0; i < this.alFieldItems.Count; i++)
{
this.sqlCmd += ((DbKeyItem)alFieldItems[i]).fieldName;
this.sqlCmd += "=";
this.sqlCmd += "@para";
this.sqlCmd += i.ToString();
this.sqlCmd += ",";
}
this.sqlCmd = Input.CutComma(this.sqlCmd);
if (this.ConditionExpress != string.Empty)
{
this.sqlCmd = this.sqlCmd + " where " + this.ConditionExpress;
}
this.cmd.CommandText = this.sqlCmd;
this.GenParameters();
int effectedLines = this.cmd.ExecuteNonQuery();
return effectedLines;
}
/// 返回查询结果DataTable
public DataTable GetDataTable()
{
DataSet ds = this.GetDataSet();
return ds.Tables[0];
}
/// <summary>
/// 根据当前指定的SqlCmd获取DataSet,如果条件表达式不为空则会被清空,
/// 所以条件表达式必须包含在SqlCmd中
/// </summary>
public DataSet GetDataSet()
{
this.ConditionExpress = string.Empty;
this.cmd.CommandText = this.sqlCmd;
this.GenParameters();
DataSet ds = new DataSet();
this.da.SelectCommand = this.cmd;
this.da.Fill(ds);
return ds;
}
/// <summary>
/// 产生OleDbCommand对象所需的参数
/// </summary>
/// <returns></returns>
protected void GenParameters()
{
if (this.alFieldItems.Count > 0)
{
for (int i = 0; i < this.alFieldItems.Count; i++)
{
cmd.Parameters.AddWithValue("@para" + i.ToString(), ((DbKeyItem)alFieldItems[i]).fieldValue.ToString());
}
}
}
#endregion
}
public class BinderItem
{
//每个绑定控件都以object的形式被存储的
public object obj;
//绑定到数据库的字段名称
public string field;
//是否是字符串类型
public bool isStringType;
/// <summary>
/// 构造函数
/// </summary>
/// <param name="_o">需要绑定的控件对象</param>
/// <param name="_field">绑定到的数据表字段名称</param>
/// <param name="_isStringType">是否是字符串类型</param>
public BinderItem(object _obj, string _field, bool _isStringType)
{
this.obj = _obj;
this.field = _field;
this.isStringType = _isStringType;
}
/// <summary>
/// 根据控件类型获得控件的值
/// </summary>
/// <returns></returns>
public string GetValue()
{
//字符串类型
if (obj is String)
{
return (string)obj;
}
//下拉框
if (obj is DropDownList)
{
DropDownList dd = (DropDownList)obj;
return dd.SelectedValue;
}
//多选框
if (obj is CheckBoxList)
{
string s = string.Empty;
CheckBoxList cb = (CheckBoxList)obj;
for (int i = 0; i < cb.Items.Count; i++)
{
if (cb.Items[i].Selected)
{
s += cb.Items[i].Value + ",";
}
}
return s;
}
//文本框
if (obj is TextBox)
{
TextBox tbx = (TextBox)obj;
return tbx.Text.Trim();
}
//Label
if (obj is Label)
{
Label lbl = (Label)obj;
return lbl.Text;
}
//单选组
if (obj is RadioButtonList)
{
RadioButtonList rb = (RadioButtonList)obj;
return rb.SelectedValue;
}
return string.Empty;
}
/// <summary>
/// 根据控件类型设定控件的值
/// </summary>
/// <param name="_value">要设定的值</param>
public void SetValue(string _value)
{
//字符串类型
if (obj is string)
{
string s = (string)obj;
s = _value;
return;
}
//文本框
if (obj is TextBox)
{
TextBox tbx = (TextBox)obj;
tbx.Text = _value;
return;
}
//单选按钮
if (obj is RadioButtonList)
{
RadioButtonList rb = (RadioButtonList)obj;
rb.SelectedValue = _value;
return;
}
//下拉列表
if (obj is DropDownList)
{
DropDownList dd = (DropDownList)obj;
dd.SelectedValue = _value;
return;
}
}
}
/// <summary>
/// 数据表中的字段属性:字段名,字段值
/// </summary>
public class DbKeyItem
{
/// <summary>
/// 字段名称
/// </summary>
public string fieldName;
/// <summary>
/// 字段值
/// </summary>
public string fieldValue;
public DbKeyItem(string _fileName, object _fieldValue)
{
this.fieldName = _fileName;
this.fieldValue = _fieldValue.ToString();
}
}
}
return;
}
//单选按钮
if (obj is RadioButtonList)
{
RadioButtonList rb = (RadioButtonList)obj;
rb.SelectedValue = _value;
return;
}
//下拉列表
if (obj is DropDownList)
{
DropDownList dd = (DropDownList)obj;
dd.SelectedValue = _value;
return;
}
}
}
/// <summary>
/// 数据表中的字段属性:字段名,字段值
/// </summary>
public class DbKeyItem
{
/// <summary>
/// 字段名称
/// </summary>
public string fieldName;
/// <summary>
/// 字段值
/// </summary>
public string fieldValue;
public DbKeyItem(string _fileName, object _fieldValue)
{
this.fieldName = _fileName;
this.fieldValue = _fieldValue.ToString();
}
}
}
声明:本网页内容旨在传播知识,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。TEL:177 7030 7066 E-MAIL:11247931@qq.com