concurrency-columns.aspx
来自「Professional ASP.NET source code」· ASPX 代码 · 共 244 行
ASPX
244 行
<%@Page Language="C#" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.OleDb" %>
<%@ Register TagPrefix="wrox" TagName="connect" Src="..\global\connect-strings.ascx" %>
<!DOCTYPE HTML PUBLIC "-// W3C// DTD HTML 4.0 Transitional// EN">
<html><head>
<title>Managing Concurrent Updates to Individual Columns</title>
<!-- #include file="..\global\style.inc" -->
</head>
<body bgcolor="#ffffff">
<span class="heading">Managing Concurrent Updates to Individual Columns</span><hr />
<!--------------------------------------------------------------------------->
<%// -- insert connection string script --%>
<wrox:connect id="ctlConnectStrings" runat="server"/>
<div>Connection string: <b><span id="outConnect" runat="server"></span></b></div>
<div>SELECT command: <b><span id="outSelect" runat="server"></span></b></div>
<div id="outError" runat="server"> </div>
<b>Initial contents of the Books table:</b>
<asp:datagrid id="dgrResult1" runat="server" /><p />
<b>Contents of the Books table after editing:</b>
<asp:datagrid id="dgrResult2" runat="server" /><p />
<div id="outConcurrent" runat="server"></div><p />
<b>The Modified records in the new DataSet:</b>
<asp:datagrid id="dgrResult3" runat="server" /><p />
<div id="outUpdates" runat="server"></div><p />
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e)
{
// get connection string from ..\global\connect-strings.ascx user control
string strConnect = ctlConnectStrings.OLEDBConnectionString;
outConnect.InnerText = strConnect; // and display it
// specify the SELECT statement to extract the data
string strSelect = "SELECT * FROM BookList WHERE ISBN LIKE '18610016%'";
outSelect.InnerText = strSelect ; // and display it
// create a new DataSet object
DataSet objDataSet = new DataSet();
// create a new Connection object using the connection string
OleDbConnection objConnect = new OleDbConnection(strConnect);
// create a new DataAdapter using the connection object and select statement
OleDbDataAdapter objDataAdapter = new OleDbDataAdapter(strSelect, objConnect);
try
{
// fill the dataset with data from the DataAdapter object
objDataAdapter.Fill(objDataSet, "Books");
}
catch (Exception objError)
{
// display error details
outError.InnerHtml = "<b>* Error while accessing data</b>.<br />"
+ objError.Message + "<br />" + objError.Source;
return; // and stop execution
}
// accept the changes to "fix" the current state of the DataSet contents
objDataSet.AcceptChanges();
// declare a variable to reference the Books table
DataTable objTable = objDataSet.Tables["Books"];
// display the contents of the Books table before changing data
dgrResult1.DataSource = objTable.DefaultView;
dgrResult1.DataBind(); // and bind (display) the data
//----------------------------------------------------------------
// now modify the DataSet by changing some records in the Books table
objTable.Rows[0]["Title"] = "Amateur Double Glazing for Windows 2000";
objTable.Rows[2]["Title"] = "Amateur Topfix Hinges for Windows 2000";
objTable.Rows[2]["PublicationDate"] = "2001-09-03";
objTable.Rows[3]["PublicationDate"] = "2001-02-08";
// display the contents of the Books table after changing the data
dgrResult2.DataSource = objTable.DefaultView;
dgrResult2.DataBind(); // and bind (display) the data
//-------------------------------------------------------------------
// change some values in the original table while the DataSet is holding
// a disconnected copy of the data to force a concurrency error
string strConcurrent = String.Empty;
string strUpdate = String.Empty;
int intRowsAffected;
// need a new (separate) Connection and Command object
OleDbConnection objnewConnect = new OleDbConnection(strConnect);
OleDbCommand objnewCommand = new OleDbCommand();
objnewCommand.Connection = objnewConnect;
try
{
objnewConnect.Open();
// modify two of the book titles to force concurrency errors
strConcurrent += "<b>Concurrently executed</b>:<br />";
DateTime datNow = DateTime.Now;
string strNow = datNow.ToString("dd-M-yy \\a\\t hh:mm:ss");
strUpdate = "UPDATE BookList SET Title = 'new Book Written on "
+ strNow + "' WHERE ISBN = '1861001622'";
objnewCommand.CommandText = strUpdate;
intRowsAffected = objnewCommand.ExecuteNonQuery();
strConcurrent += strUpdate + "<br /> ... <b>"
+ intRowsAffected.ToString() + "</b> row(s) affected<br />";
// edit the next line to force a concurrency error if none occurs
strUpdate = "UPDATE BookList SET Title = 'Another Book Written on "
+ strNow + "' WHERE ISBN = '1861001681'";
objnewCommand.CommandText = strUpdate;
intRowsAffected = objnewCommand.ExecuteNonQuery();
strConcurrent += strUpdate + "<br /> ... <b>"
+ intRowsAffected.ToString() + "</b> row(s) affected<br />";
objnewConnect.Close();
}
catch (Exception objError)
{
// display error details
outError.InnerHtml = "<b>* Error while updating original data</b>.<br />"
+ objError.Message + "<br />" + objError.Source;
return; // and stop execution
}
outConcurrent.InnerHtml = strConcurrent;
//----------------------------------------------------------------
// now start the process of collecting the changed values and
// updating the original data source
string strSQL, strWhere, strRowValue, strResults, strColName;
DateTime datRowDateValue;
// create a new Command object to use for the updates
OleDbCommand objCommand = new OleDbCommand();
// specify the Connection object and command type for the Command
objCommand.Connection = objConnect;
objCommand.CommandType = CommandType.Text;
// declare a variable to hold a new DataSet object
DataSet objChangeDS;
// get *changed* records into the new DataSet
// copies only rows with a RowState property of "Modified"
objChangeDS = objDataSet.GetChanges(DataRowState.Modified);
// display the modified records in the table in the new DataSet
dgrResult3.DataSource = objChangeDS.Tables[0].DefaultView;
dgrResult3.DataBind(); // and bind (display) the data
// open connection and apply the updates to the data source
objConnect.Open();
// declare a variable to hold a Transaction object
OleDbTransaction objTransaction;
// start a transaction and assign it to the current Command object
objTransaction = objConnect.BeginTransaction();
objCommand.Transaction = objTransaction;
strResults = "<b>Executing Update Commands</b> ...<br />";
// iterate through all the modified rows in the table
foreach (DataRow objRow in objChangeDS.Tables[0].Rows)
{
// create the two root parts of the SQL statement
strSQL = "UPDATE BookList SET ";
strWhere = " WHERE ISBN='"
+ objRow["ISBN", DataRowVersion.Original] + "'";
// iterate through all the columns in this row
foreach (DataColumn objColumn in objChangeDS.Tables[0].Columns)
{
strColName = objColumn.ColumnName;
// see if this column has been changed since the DataSet was
// originally created by comparing Original and Current values
if (objRow[strColName, DataRowVersion.Current] !=
objRow[strColName, DataRowVersion.Original])
{
// this column// s data has been modified in the disconnected DataSet
// note: this does not detect concurrent changes to the source data
// have to get format of DateTime exactly right for a comparison
if (objColumn.DataType.ToString() == "System.DateTime")
{
datRowDateValue = (DateTime)objRow[strColName, DataRowVersion.Original];
strRowValue = datRowDateValue.ToString("yyyy-MM-dd HH:mm:ss");
}
else
{
strRowValue = objRow[strColName, DataRowVersion.Original].ToString();
}
strSQL += strColName + "='" + objRow[strColName, DataRowVersion.Current] + "', ";
strWhere += " AND " + strColName + "='" + strRowValue + "'";
}
}
// strip off extra comma and space from end of string
strSQL = strSQL.Substring(1, strSQL.Length - 2) + strWhere;
// and assemble SQL statement
strResults += "* " + strSQL + " ... ";
objCommand.CommandText = strSQL;
try
{
intRowsAffected = objCommand.ExecuteNonQuery();
if (intRowsAffected > 0)
strResults += "updated <b>" + intRowsAffected + "</b> row(s).<p />";
else
strResults += "<b>Error</b>: Row has been changed by another user<p />";
}
catch (Exception objError)
{
// display error details
strResults += "<b>Error</b>: " + objError.Message + " - " + objError.Source + "<p />";
}
}
outUpdates.InnerHtml = strResults;
objTransaction.Rollback();
objConnect.Close();
}
</script>
<!--------------------------------------------------------------------------->
<!-- #include file="..\global\foot.inc" -->
</body>
</html>
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?