題外話:我為什麼研究小孔子的cms,從我自己寫一個cms我就開始研究起別人的cms,早期我是研究netcms,但這系統過於龐大,看上去十分的累,也沒那個精力,於是打算從一套比較小的開始研究,於是小孔子cms就進入了我的研究范圍。沒過多久我就放下我手中的cms,決定研究清楚有了更多經驗再繼續寫完我沒有完成的cms。
最近都在看小孔子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();
}
}
}