Unable to Retrieve Microsoft Access Autonumber Values - c#

Access 2003
VS 2010 C#
As subject title says I am having a problem with this. It's creating a new field to print date and time when it should be stamping the date and time in the current ID. I have also tried UPDATE command parameter without success.
I have a different method (btnloggedIn) which saves Usernames, Logged In Date and Logged In Time. This works as it should be. I have created another method (btnLoggedOut) which I am having problems with. The purposes is to save Logged Out Date and Logged Out Time when user who logged out, in the came column in Access where Auto ID is created when logged in.
Table Name - LoginTable
>
FieldName Data Type
UserName Text
Password Text
Table name - LoginLogTable
FieldName Data Type
ID AutoNumber
UserName Text
LoggedInDate Date/Time
LoggedInTime Date/Time
LoggedOutDate Date/Time
LoggedOutTime Date/Time
ID is PK. Its one to many relationship. User who logs in can have many details about the date and time details
If anyone can help me here I would be grateful.
private void btnLogOut_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " UPDATE [LoginLogTable] SET [LoggedOutDate] = ?, [LoggedOutTime] = ?
WHERE 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();
}
This the partial code for btnLogin method...
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
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();
myCon.Close();

If you execute a SELECT ##IDENTITY query when the user clicks the "Log out" button you'll not likely get the value you're hoping for. SELECT ##IDENTITY is intended to be called immediately after the INSERT that creates the record (in this case, when the user logs in). You can then stash that value away in your application and use it to select that same record when the user logs out.
If your application inserts any other records (in other tables) that cause a new Identity (a.k.a. "AutoNumber") value to be created then SELECT ##IDENTITY will return the most recent one of those values. So, just grab the ##IDENTITY value when the user logs in and save it for when the user logs out again.

Typically, the way this is done is:
Create the new log in record.
Get its auto-generated record ID by running a new select asking for the newest log in entry for that particular user. You can sort descending to guarantee it is the first record in the recordset.
Use that record ID to specify the log in record you want to update using WHERE ID = ? instead and fill in the ID value with the record ID.
This is a very typical pattern for database record creation when you do not know what the auto-generated primary record ID will be. You create your new record, you read it back in the record ID to get its auto-generated primary key ID value, and then use the record ID from then on to refer to it.

Related

Getting the PK of a record before being saved on the database sqlserver and C#

Good day guys,
I am creating a system for saving details of a user, i have attributes (UserID(pk-Auto),name,surname,disability(FK)..
I have 3 tables, being
user ( UserID(pk), Name, surname, disability(fk) )
disability ( DisabilityID(pk), Disability(YES/NO) )
disabilitype ( DisabilityTypeID(PK), disabilityID(fk), UserID(fk), disabilityName )
The disability have an option of yes/now(with the id for yes being 1 and 2 for no), if the user clicks yes the system must be able to save data on disabilityType and retrieve the PK of user of which it is unknown because the user details will saved afer the if statement of the disability attribute
if you mean you want the id of the next entered row before save it you can get it by making a trick first get the last entered id.for example if you have table called user and the primary key is Id you can select last entered id by this query SELECT IDENT_CURRENT('user') and then the next id is the output value +1
You should be able to use ##Identity to get at the id that was generated by the statement. So when you insert into the User table add an out parameter that returns the ##Identity, then use that value to save int the disabilitype table accordingly.
using (SqlCommand cmd = new SqlCommand("Insert Into User ... //Brevity
RETURN ##IDENTITY
", cn)) {
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter returnValue = new SqlParameter();
returnValue.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(returnValue);
cmd.ExecuteNonQuery();
}

Insert a value in a table from another table using a variable in C# , SQL Server

I have to insert some values in a table while fetching them from another table. Here is my code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString);
SqlCommand myCommand = new SqlCommand("SELECT Name FROM TableName WHERE Id = '" + Id + "'", con);
SqlDataReader rdr = myCommand.ExecuteReader();
if (dr.HasRows)
{
while (rdr.Read())
{
// User exist - get email
string Name = rdr["Name"].ToString();
}
}
My question is how to insert the name into another table.
I do not want to use a textbox for this the value must be inserted as a variable into other table. I use following script to insert data . but error message is Id not found. Please let me know if I am missing something
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES (#string)", con);
I use following script to insert data . but error message is Id not found.
SqlCommand cmd = new SqlCommand(#"insert into finalTable (AccountNumber) VALUES
(#string)", con);
You need to specify a value for all columns in the table, unless some columns have default values. Its hard to tell without the exact error message, but it sounds like Id is probably the primary key column and not set to auto increment, so you must supply a value for Id. Since you are inserting, it must be a value not yet used in the table. Depending on your needs, you might want to change finalTable's ID to be auto increment.
On a side note, you are not disposing of things (like your DB connection) that implement IDisposable. The using keyword is your friend here.

SQL Server database last_rowID

I have a C# app with have to use SQL Server database with 1 table (All_Data) and 5 columns (ID, Name, Surename, Age,Location)
Before inserting a new row how can I find out or get the value of the last ID in the table
I have a following code but it,a not work well
string query = "SELECT MAX(ID) FROM All_Data";
SqlCommand comSelect;
comSelect = new SqlCommand(query, connection);
int ID = (int)comSelect.ExecuteScalar();
ERROR message:
ExecuteScalar: Connection property has not been initialized
Please help me
First, from your code it is not clear what is the value of the variable connection.
From the error message it seems that you don't have initialized this variable and thus you get the error. (connection = new SqlConnection(....);)
However, this is not the correct way to handle this scenario.
You need to make the ID column an IDENTITY column and then don't try to retrieve its value before executing any INSERT.
An IDENTITY column receives its value directly from the database when there is a new record to insert. And letting the database code work on this data it is the best option if you want to be safe from concurrency issues.
If you need to retrieve the ID value after an INSERT query because you need it as a Foreign Key in other tables or for your own code, then you could simply use the T-SQL command
SELECT SCOPE_IDENTITY()
For example, suppose you have to insert a record in that table, and you want to know the IDENTITY value assigned to the ID column
string query = #"INSERT INTO All_Data(Name,Surename,Age,Location)
VALUES(#name, #surname, #age, #loc);
SELECT SCOPE_IDENTITY()";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(query, connection))
{
connection.Open();
cmd.Parameters.AddWithValue("#name", yourNameValue);
.... other parameters ...
int newID = Convert.ToInt32(cmd.ExecuteScalar());
}
As you can see, this code doesn't try to pass a value for the ID column. It pass just the other fields with a parameterized query. But at the end of the first query there is a call to SELECT SCOPE_IDENTITY() and this returns whatever value the database has assigned to the column ID (of course you should have set the IDENTITY property on the field).
This will work correctly in multiuser and concurrent scenario
The error fires when the command doesn't have a connection. Please check connection is open.
Error saysExecuteScalar: Connectio property has not been initialized
double Check your connection string whether it is defined properly. You can check here to know how to define connection string.
you have not opened connection so open it before use :
comSelect = new SqlCommand(query, connection);
connection.Open();
int ID = (int)comSelect.ExecuteScalar();
connection.Close();

Determining if user login already exists in database?

I am building a web application in asp.net using C#. I have the Form where the user should register and then can login. I am having a problem in making the web app know that the name which the user picks is either "already exists" or not. If it already exists it should not insert the same name and display a message saying "user name already exists". I have tried the SqlDataReader but no luck.
protected void Register_Button_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BJ_Player_String"].ToString());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
SqlDataReader data_reader;
String name = TextBox2.Text;
String date = TextBox3.Text;
try
{
conn.Open();
cmd = new SqlCommand("Insert into BJ_Player (Player_Name, D_O_B) Values (#Player_name, #D_O_B)", conn);
cmd = new SqlCommand("Select Player_Name from BJ_Player WHERE Player_Name = #Player_name", conn);
cmd.Parameters.Add("#Player_name", SqlDbType.NVarChar).Value = name;
cmd.Parameters.Add("#D_O_B", SqlDbType.Date).Value = date;
cmd.Connection = conn;
data_reader = cmd.ExecuteReader();
cmd.ExecuteNonQuery();
if (data_reader.HasRows)
{
lblPlayerNameExists.Visible = true;
}
else
{
// do nothing
}
}
Make Player_Name unique in database then it will give you exception when you try to insert. You have to use unique constraint.
You have to give command type also and check you assigned both queries to same cmd object
in your code you're inserting data in your DB and then you are examining that the name is the same or not.
first you should search the name in your DB and then if there isn't any record with that name ,you should add your record.
I usually do it in one of two ways:
Create stored procedure that will check for name uniqueness and insert new record if everything is ok. It should return status as numeric code that you will check.
Check for name uniqueness before saving it using as a part of validation process.
Using the merge statement may help with this. Merge performs insert, update, or delete operations on a target table based on the results of a join with a source table.
Basically it inserts when needed, and updates when needed. Often times referred to as an upsert. but it gets the job done.
Here is a link to a site explaining how to use merge. Looks like a good article.
http://www.kodyaz.com/articles/sql-server-2008-t-sql-merge-statement-example.aspx
If you would like to write a model function to do that then
Leave it for ajax check which is pretty similar to the second
method
Issue "Select username from DB-table" to retrieve
usernames then check the username input against them before
displaying a view to report a problem if any or showing a message to
tell the user that "this name is valid", for example.

SQL Server database query

I have used the standard user tables that ASP.net setup and I'm looking to be able to delete users. To do this first off I need to delete the user id from a table called memberships and then delete the user. To do this I have 2 text boxes setup one for user id and other for user name.
Any ideas of a T-SQL statement that will delete the membership user id first and then move onto the delete username this is my statement so far
else
{
try
{
connection.Open();
cmd = new SqlCommand("DELETE from Membershio
WHERE UserId ='" + deleteuserIDbox.Text + "'", connection);
cmd = new SqlCommand("DELETE from Users WHERE UserName ='" + deleteuserbox.Text + "'", connection);
cmd.ExecuteNonQuery();
update.Text = "Your data has been removed";
}
catch
{
update.Text = "Your data has not been deleted";
}
}
The two tables are related hence I need to delete the user id first and then the username
any help greatly appricated
If understand it right, your input method has serious issues.
For example,
UserID UserName
1 testUser
2 testUser2
With the logic in your application; I can enter "1" into deleteuserIDbox and "testUser2" into deleteuserbox which in turn would remove userID 1 but not username "testUser".
If you didn't do it already, you need to associate those two tables using Foreign Key on UserID. So the linkage is persisted with UserID field.
Another issue is, you are directly executing the query with the input from user thus enabling the possiblity of sql injection.
About your query, you can put " cmd.ExecuteNonQuery();" between your two cmd statements.
To use your current code, you will need to execute the first query, then set the CommandText for the second query and execute that.
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = "DELETE FROM Membership WHERE UserID = #UserID";
cmd.Parameters.AddWithValue("#UserID", deleteuserIDbox.Text);
connection.Open();
cmd.ExecuteNonQuery();
cmd.Paramters.Clear();
cmd.CommandText = "DELETE from Users WHERE UserName = #UserName";
cmd.Parameters.AddWithValue("#UserName", deleteuserbox.Text);
cmd.ExecuteNonQuery();
}
Another option is to use a stored procedure that would allow you to run the two queries together.
Another option is to do cascading deletes. Here is a link on how to accomplish that.
Lastly, you are opening yourself up to SQL Injection. You should NEVER take input from a user and concatenate that data into a SQL statement. You should either use a Stored Procedure or a parameterized query(like I used above).
You're not executing the first command:
connection.Open();
cmd = new SqlCommand("DELETE from Membershio
WHERE UserId ='" +
deleteuserIDbox.Text + "'", connection);
cmd.ExecuteNonQuery();
cmd = new SqlCommand("DELETE from Users WHERE
UserName ='" + deleteuserbox.Text +
"'", connection);
cmd.ExecuteNonQuery();
Also, these commands should be executed in a transaction.
A bit late but I only noticed your question today.
By doing this on the database you are bypassing all the good stuff! You should do this in C# by calling the Membership::DeleteUser Method
http://msdn.microsoft.com/en-us/library/5xxz7y3a.aspx
You should not mess with the internals of the Membership system at all.

Categories