Get the identity of the last updated row in SQL via C# - c#

I am trying to first create a new row in my SQL Compact Edition database via C# and then I want to update the same row with information in my radiobuttons. I have an "ID" column in the database which is auto incremental.
So I tried to assign its value to a variable using ##Identity and call it in the update query but it doesn't work. I've tried MAX to find the max value in ID column which will be the latest row but it still didn't work. Here's my code.
con.Open();
string sqlAdd = "Insert into MembersTable ([First Name],Surname,[Middle Name])
Values('"+txtFirstName.Text+"','"+txtSurname.Text+"','"+ txtMiddleName.Text+"')";
string IDIdentifier = "Select ##Identity AS TempID";
string sqlgenderM = "Update MembersTable set Gender='M' where ID='" + DC.ID + "'";
string sqlgenderF = "Update MembersTable set Gender='F' where ID='" + DC.ID + "'";
com = new SqlCeCommand(sqlAdd, con);
com.ExecuteNonQuery();
SqlCeCommand com1 = new SqlCeCommand(IDIdentifier, con);
SqlCeDataReader dr1 = com1.ExecuteReader();
if (dr1.Read())
{
DC.ID = dr1["TempID"].ToString();
}
{
if (rbGenderMale.Checked == true)
{
SqlCeCommand gendercom = new SqlCeCommand(sqlgenderM, con);
gendercom.ExecuteNonQuery();
}
else if (rbGenderFemale.Checked == true)
{
SqlCeCommand gendercom = new SqlCeCommand(sqlgenderF, con);
gendercom.ExecuteNonQuery();
}
}
The fields (First Name, Middle Name, Surname) get updated but the Gender columns don't. What am I doing wrong?

Thanks to #Soner I used:
int.TryParse(dr1["TempID"].ToString(), out Identity);
string IdentityS = Identity.ToString();
and replaced DC.ID with IdentityS
Now it works perfectly.

Related

ExecuteScalar() always returns NULL even though there is data in the database

I am trying to make a simple memory game on visual Studio using C#. This game must keep some user records in the database. My database is not empty. This is part of my code :
string ConnectionString = #"Data Source =" + Application.StartupPath + #"\mydb.sdf";
SqlCeConnection sqlConnection1 = new SqlCeConnection(#"Data Source=" +Application.StartupPath + #"\mydb.sdf");
System.Data.SqlServerCe.SqlCeCommand cmdt = new System.Data.SqlServerCe.SqlCeCommand(ConnectionString);
cmdt.CommandText = "insert into logs (Sessionid, score, Minutes, Hintcount, Errorcount, Level, Picname) values(#ID, #Score, #Minutes, #Hintcount, #Errorcount, 'Level 1', #Picname)";
cmdt.Connection = sqlConnection1;
sqlConnection1.Open();
{
SqlCeCommand cmd = new SqlCeCommand("select ID from Userrecords where ID=(select MAX(ID) from Userrecords) and Username='" + LoginInfo.UserID + "'", sqlConnection1);
cmd.UpdatedRowSource = UpdateRowSource.OutputParameters;
int id = (int)cmd.ExecuteScalar();
cmdt.Parameters.AddWithValue("#Score", point);
cmdt.Parameters.AddWithValue("#Minutes", time);
cmdt.Parameters.AddWithValue("#Hintcount", hbuttoncount);
cmdt.Parameters.AddWithValue("#Errorcount", errorcount);
cmdt.Parameters.AddWithValue("#Picname", nameused2);
cmdt.Parameters.AddWithValue("#ID", id);
cmdt.UpdatedRowSource = UpdateRowSource.OutputParameters;
cmdt.ExecuteNonQuery();
sqlConnection1.Close();
}
I am trying to use executeScalar method, in order to retrieve the session ID from another table. But it always returns NULL, so it throws an exception. Is there any alternative that i can use?
I think you want the latest ID for this Username, then your query is wrong. Use:
var sql = #"SELECT MAX(ID) As Id
FROM Userrecords
WHERE Username = #UserName";
SqlCeCommand cmd = new SqlCeCommand(sql, sqlConnection1);
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = LoginInfo.UserID;
Your query returned the max-id if this record accidentially had the searched Username.

How do I check Duplicate [duplicate]

This question already has an answer here:
how to i search if there is a same id in a database?
(1 answer)
Closed 6 years ago.
private void Add_Box_Click(object sender, EventArgs e)
{
string phoneNumber;
if (string.IsNullOrWhiteSpace(Id_Box.Text))// To check if the Id_box is empty or not
{
MessageBox.Show("Please Enter Your ID");// need to enter ID in order to save data
}
///////////////////////////////////////////check the Extension Box////////////////////////////////////////////////////////////////////////////////////
else
{
if (string.IsNullOrWhiteSpace(Ext_Box.Text))
{
phoneNumber = Phone_Box.Text;// if it is empty then it will only show the phone number
}
else
{
phoneNumber = Phone_Box.Text + "," + Ext_Box.Text; // show the phone number and the extension if there is something in the extension
}
///////////////////////////////////////////////////////////Save it to the Database///////////////////////////////////////////////////////
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Contact_List(Id, Name, Adress1, Adress2, City, Province, Postal_Code, Phone, Email)VALUES('" + Id_Box.Text + "','" + Name_Box.Text + "','" + Adress1_Box.Text + "','" + Adress2_Box.Text + "','" + City_Box.Text + "','" + Province_Box.Text + "','" + Code_Box.Text + "','" + phoneNumber + "','" + Email_Box.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Information Added", "Confirm");
/////////////////////////////////////Show new set of data after insert a new data/////////////////////////////////////////////////////////////
SqlCeCommand cmd2 = new SqlCeCommand("Select * from Contact_List;", con);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmd2;
DataTable dt = new DataTable();
sda.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource = bs;
sda.Update(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
////////////////////////////////Empty The Box/////////////////////////////////////////////////////////////////////////////////////////////////
Id_Box.Text = String.Empty;
Name_Box.Text = String.Empty;
Adress1_Box.Text = String.Empty;
Adress2_Box.Text = String.Empty;
City_Box.Text = String.Empty;
Province_Box.Text = String.Empty;
Code_Box.Text = String.Empty;
Phone_Box.Text = String.Empty;
Ext_Box.Text = String.Empty;
Email_Box.Text = String.Empty;
}
}
This code will store Id, name, etc to the database. But when there is a same Id, i want to delete it. When i delete it both of the same Id will be deleted and i don't want that so is there anyway to check duplicate before it store it to the database?
I want to do something like this if possible :
if ( the values in id column == to the Id_textBox) {
MessageBox.Show("Duplicate ,PLease enter anotherId")
}
Possible?
Before executing your INSERT SQL statement, try running the SQL int ContactCount = (int)cmd.ExecuteScalar("SELECT COUNT(*) FROM CONTACT_LIST WHERE Id = '" + Id_Box.Text + "'")
If ContactCount > 0 then you can do the DELETE your suggesting.
Can I also recommend that you use a SQL UPDATE instead of DELETEing and INSERTing the same record.
Also, read-up on SQL Injection attacks. Building a SQL statement, like you're doing here, using the values input by a user leaves you exposed to that type of vulnerability.
First of all, like in all these answers: Don't use string concatenation but parametrized queries to prevent SQL-injection.
For your problem:
You can either do a
string query = "SELECT count(*) from ContactList Where id = #id";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = (int)cmd.ExecuteScalar();
if count > 0 the id already exists.
Or you can do a
string query "IF NOT EXISTS(SELECT count(*) from ContactList Where id = #id) INSERT INTO ContactList(Id, ...) VALUES(#id, ...)";
SqlCeCommand cmd = new SqlCeCommand(query, connection);
cmd.Parameters.Add("#id", SqlDbType.NVarChar, 50).Value = Id_Box.Text;
int count = cmd.ExecuteNonQuery();
count will then contain the number of rows affected, ie 0 if the value already existed, or 1 if it did not exist, but was newly inserted.

More efficient way of running multiple update queries on an Access database?

I have multiple queries like this right now which involve updating different fields of the same row in an Access database:
//Update database
string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?";
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" + #"Data Source=" + "database.accdb");
con.Open();
OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con);
var accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//update last10attemptssum
updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
//increment totalquestionattempt
updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?";
accessUpdateCommand = new OleDbCommand(updatequery, con);
accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1);
da.UpdateCommand = accessUpdateCommand;
da.UpdateCommand.ExecuteNonQuery();
con.Close();
I was wondering if there is a more efficient way of running these update queries - ie. combining them into one query.
There is no need to use an OleDbDataAdapter in your context above. You could use a simple command and execute it
Said that, an Update sql statement can update more than one field. Just write
string updatequery = #"UPDATE [table] SET [Last10Attempts] = ?,
[Last10AttemptsSum] = ?,
[total-question-attempts] = ?
WHERE id = ?";
using(OleDbConnection con = new OleDbConnection(.........))
using(OleDbCommand cmd = new OleDbCommand(updatequery, con))
{
con.Open();
cmd.Parameters.AddWithValue("Last10Attempts", last10attempts);
cmd.Parameters.AddWithValue("Last10AttemptsSum", counter);
cmd.Parameters.AddWithValue("total-question-attempts", questionattempts + 1);
cmd.Parameters.AddWithValue("ID", currentid + 1);
cmd.ExecuteNonQuery();
}
The only thing to keep present when working with OleDb is the fact that the parameters are used in the exact order in which the parameter placeholder appears in the command text. So they should be added to the parameter collection in the order expected by the command text

"The data type is not valid for the boolean operation."

I am trying to select a set of data for a ComboBox based on the selection of the previous ComboBox. I have been lead to believe it is the SELECT statement in the second method, but I cannot figure out why it isn't working. When I run the application I receive this error:
The data type is not valid for the boolean operation. [Data type (if
known) = int,Data type (if known) = nvarchar ].
I have attempted using Parameter.AddWithValue and also setting the value as a string to no avail. Would anyone mind teaching me how to correctly resolve this? Thank you.
private void cboCities_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboCities.SelectedIndex > -1)
{
SqlCeConnection cn = new SqlCeConnection(#"Data Source = \Program Files\ParkSurvey\ParkSurvey.sdf; Persist Security Info = False; Password = *");
cn.Open();
SqlCeCommand cmd = cn.CreateCommand();
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId ='" + cboCities.SelectedValue + "'ORDER BY Name ASC";
SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
cn.Close();
cboParks.ValueMember = "ParkId";
cboParks.DisplayMember = "Name";
cboParks.DataSource = ds.Tables[0];
cboParks.SelectedIndex = -1;
}
Have you tried something like the following?
//[...code...]
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId = #CityId ORDER BY Name ASC";
cmd.Parameters.Add("#CityId", System.Data.SqlDbType.Int, 2).Value = Convert.ToInt32(cboCities.SelectedValue);
//[...code...]
Is the CityId in the Parks table is an integer?
You are comparing an int ie CityId to a string '...value in cboCities.SelectedValue ...'
Try casting the City it to and integer :
cmd.CommandText = "SELECT Name FROM Parks WHERE CAST(CityId AS NVARCAR) ='" + cboCities.SelectedValue + "'ORDER BY Name ASC";
Or if you are sure that the in cboCities.SelectedValue is the same as CityId you can also try it without the quotes (an integer to integer comparison)
cmd.CommandText = "SELECT Name FROM Parks WHERE CityId = " + cboCities.SelectedValue + " ORDER BY Name ASC";
(note I've removed the single quotes around cboCities.SelectedValue)

How to check if record exists or not and insert in ms access database in c#

I want to check if record exists or not if it exists i dont want to insert if it bot i want to insert the data in ms access database in c#.
OleDbCommand cmd = new OleDbCommand("insert into MyTable values('" + test + "','" + test + "','" + "123" + "');", con);
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);
temp = 0;
try
{
con.Open();
string count = (string)cmd1.ExecuteScalar();
temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
MessageBox.Show("One Record Added");
}
else
{
MessageBox.Show("Record not added");
}
}
catch
{ }
Can Anyone suggest me some code.
Thanks In Advance.
Filter your Select query on the basis of some key . Check if it returns for existence or non-existence of the particular record and do the processing required .
string cmdStr = "Select count(*) from MyTable where id = 1"; //get the existence of the record as count
OleDbCommand cmd = new OleDbCommand(cmdStr, conn);
int count = (int)cmd.ExecuteScalar();
if(count >0)
{
//record already exist
}
Modify this line
OleDbCommand cmd1 = new OleDbCommand("select * from MyTable", con);

Categories