|
| Retrieve Primary Key value from a just-inserted row |
 |
Thu, 3 Apr 2008 03:16:30 +0000 |
I'm trying to get the PrimaryKey automatically assigned by my Access Database
when I insert a new row so I can store it in a session variable, but when it
executes, I get an error saying that no value exists for the column. I know
from looking at the data that the row is being inserted. Any idea what's amiss
with my approach?
try
{
// Insert new customer record
srcCustomers.Insert();
// Store customer ID as session variabletry
{
OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = srcCustomers.ConnectionString;
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT CustomerID " +
"FROM tCustomers " +
"WHERE LastName ='" + txtLastName +
"'" +
"AND FirstName = '" + txtFirstName +
"'" +
"AND EmailAddress = '" + txtEmail +
"'";
cn.Open();
//int CustomerID = (int)cmd.ExecuteScalar();
//Session["CustomerID"] = CustomerID;
OleDbDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Session["CustomerID"] = rdr["CustomerID"];
rdr.Close();
cn.Close();
lblStatus.Text = "New customer ID = " +
((int)Session["CustomerID"]).ToString();
}
catch (Exception ex1)
{
lblStatus.Text = "Unable to retrieve customer ID: " +
ex1.Message;
}
}
catch (Exception ex)
{
lblStatus.Text = "Unable to store data: " + ex.Message;
}
|
| Post Reply
|
| Re: Retrieve Primary Key value from a just-inserted row |
 |
Thu, 3 Apr 2008 06:20:48 +0000 |
When using MS Access it has to be done in a two step process upon insert. So,
for example you run the insert and perform DataSet.Update() and then need to
have a handler get the @@IDENTITY from the database.
Check out http://msdn2.microsoft.com/en-us/library/ks9f57t0(vs.71).aspx
This has a great example. It is different than what your code shows above.
|
| Post Reply
|
| Re: Retrieve Primary Key value from a just-inserted row |
 |
Thu, 3 Apr 2008 06:51:50 +0000 |
Getting the identity of the most recently added record:
http://www.mikesdotnetting.com/Article.aspx?ArticleID=54
|
| Post Reply
|
|
|
|
|
|
|
|
|
|