Access 2003
VS 2010 C#
As subject title says I am having problems with. This is related to my previous question I asked, Here. I hope the mod's will be OK with this thread but I am not sure.
Martin Parkin advised not to close the connection between Insert and Select when using ##Identity with C# and MS-Access. I thought I got it working until I discovered that was not the case. To be honest I don't know how to solve this issue. So if anyone can help me I would appreciate it.
This is my btnLogin method..
cmd.CommandText = "INSERT INTO LoginLogTable (UserName, LoggedInDate, LoggedInTime) VALUES (#UserName, #LoggedInDate, #LoggedInTime)";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedInDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedInTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT #ID = ##IDENTITY";
// cmd.Parameters.AddWithValue("#ID", OleDbType.WChar); << tried this, unsuccessful
int id = (int)cmd.ExecuteScalar(); // getting the same error?
myCon.Close();
This is my btnLogOut method...
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
int id = 0;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
Close();
Or
In the btnLogin method if I do
cmd.CommandText = "SELECT #ID = ##IDENTITY";
and hide the cmd.ExecuteNonQuery(); after it. Then date and time will get logged in the database but the date and time will not get saved in the database, for logging out.
I am not sure if the problem is with btnLogin method or btnLogOut method, or both.
Working Solution
Originally I did
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate,
[LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
Then I did this
cmd.CommandText = " UPDATE [LoginLogTable] SET [UserName] = #UserName, [LoggedOutDate] =
#LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE ID = #ID";
cmd.Parameters.AddWithValue("#UserName", txtUserName.Text);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
cmd.Parameters.AddWithValue("#ID", id);
Thanks to D Stanley and Gord Thompson.
The #ID variable does not persist in the database the way you seem to think it does. It will go out of scope when the connection is closed (possibly sooner). I would advise that you store the new identity within your application instead:
Assuming these are button handlers that are methods on the form, you could store the ID as a property of the form:
// somewhere in the form definition:
private int ID {get; set;}
...
cmd.CommandText = "SELECT ##IDENTITY";
int id = (int)cmd.ExecuteScalar();
this.ID = id;
Then use the ID in your Logout method:
// get the id from the form
int id = this.ID;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = #LoggedOutDate, [LoggedOutTime] = #LoggedOutTime WHERE [ID] = #ID";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#LoggedOutDate", DateTime.Now.ToShortDateString());
cmd.Parameters.AddWithValue("#LoggedOutTime", DateTime.Now.ToString("HH:mm"));
Related
I want to insert email in Table with only one column. I tried on 2 way. First time I tried with commandText and second time I tried with parapeters. But the both solution give me the same error.
System.Data.OleDb.OleDbException: 'Syntax error in INSERT INTO statement.'
I don't see any error in INSERT STATEMENT. Maybe the problem is in TABLE?
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "SELECT COUNT (email) FROM [User] WHERE [email] LIKE '" + userEmail + "';";
conn.Open();
int count = Convert.ToInt32(cmd.ExecuteScalar()); // This passed
if (count == 0)
{
string query = #"INSERT INTO User (email) VALUES (#email)";
string cmdText= #"INSERT INTO User (email) VALUES ('"+userEmail+"')";
OleDbCommand command = new OleDbCommand(cmdText, conn);
// command.Parameters.AddWithValue("#email", "userEmail");
// command.CommandText = query;
command.ExecuteNonQuery(); // I GOT ERROR HERE
}
conn.Close();
}
User is a keyword. You should INSERT INTO [USER] instead
string cmdText= #"INSERT INTO User (email)) VALUES ('"+userEmail+"')";
you have one ')' too many after (email)
I have this code, and when I execute it, it doesn't work
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = 'username', pass = '#password' where IDetudient='#ID ' ", con);
con.Open();
cmd.Parameters.AddWithValue("#username", text_name.Text);
cmd.Parameters.AddWithValue("#password",Convert.ToDecimal( textBox1.Text));
cmd.Parameters.AddWithValue("#ID", Convert.ToInt64( text_id.Text));
cmd.ExecuteNonQuery();
con.Close();
Try this way:
SqlCommand cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient=#ID", con);
I had the same issue. The thing is, in the query you just pass the name of the parameter.
Your sql command't test would be:
var cmd = new SqlCommand("UPDATE etudient SET [nom etudient] = #username, pass = #password where IDetudient = #ID ", con);
Also, you will need to validate if conversion from string to int64 if fails or not.
I want to update some columns on my table but ExecuteNonQuery doesn't respond (Timeout). Did I do something wrong?
Notes: in the database table, id is integer, F1 varchar2 and the parameters I am sending are string and int.
try {
using (OracleConnection con = new OracleConnection(ConString)) {
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = "UPDATE DB.Table "+
"SET F1= :yd" +
"WHERE ID = :id";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("yd", yd);
cmd.Parameters.Add("id", id);
cmd.ExecuteNonQuery();
con.Close();
return true;
}
}
catch (Exception ex) {
return false;
}
Thanks
It can be solved by committing or roll backing pending transactions on your Oracle developer or any other IDEs running on your machine.
You're mixing up your parameter names. There is no parameter named "F1" in your query, use "yd".
cmd.CommandText = "UPDATE DB.Table "+
"SET F1= :yd" +
"WHERE ID = :id";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("yd", yd);
cmd.Parameters.Add("id", id);
I found that is because of other program like toad locks the query. After commiting all thing in toad, everything is solved.
Thanks for all for helping. I love you guys, i like brainstorming :)
cmd.Connection = con;
string qry = "UPDATE DB.Table "+"SET F1= #yd" +"WHERE ID = #id";
OracleCommand cmd = new OracleCommand(qry,con);
cmd.Parameters.AddWithValue("#yd", yd);
cmd.Parameters.AddWithValue("#id", id);
cmd.ExecuteNonQuery();
I am trying to get all the details of a User in an Access database. But i cant seem to save each columns value to a label. Here is the code i am using.
Also UserId has a value assigned to it already
string connString = (#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=DataDirectory|HorseDB.mdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId ";
cmd.Parameters.AddWithValue("#UserId", UserId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
accountUserIdLabel.Text = dbReader.GetValue(0).ToString();
//Will add other labels once this works
}
dbReader.Close();
conn.Close();
i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.