Check for duplicate entries before insertion (C#.net) - c#

I have a textbox form that students fill out about their general information such as first and last name, city, state, etc. Sometimes a student can't remember if they filled out the form before and it will lead to duplicate entries in the ms-access database. Ideally I would like the code to first search the ms-access database for a matching first name AND last name on the same record before insertion. If there's a record that matches on both the entered first and last name fields then a script would run and say something like, "A matching record already exists, would you like to continue?" Clicking "Yes" would enter the record into a new row, clicking "Cancel" would not enter it into the database at all.
I started this code but I'm not sure if it's the right direction, any guidance would be appreciated, thanks.
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
(This is where I am stuck)
}
}
Below is the current code for the submit button.
protected void btnSubmit_Click(object sender, EventArgs e)
{
{
//Preforms insert statement on click to allow additions to the database
DateTime CurrentDate;
CurrentDate = DateTime.Now;
string constr = #"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\sites\schoolinfo\students_dev\App_Data\Studentdb.mdb";
string cmdstr = "INSERT into StudentList(FName, LName, BDay, Gender, School, Grade, Address, APT, City, State, Zip, Email, Phone, CellPhone, ParentFName, ParentLName, ParentEmail) values(#FName, #LName, #BDay, #Gender, #School, #Grade, #Address, #APT, #City, #State, #Zip, #Email, #Phone, #CellPhone, #ParentFName, #ParentLName, #ParentEmail)";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(cmdstr, con);
{
con.Open();
}
//The following fields are added from the student information to the corresponding database fields
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
com.Parameters.AddWithValue("#BDay", txtBirthDate.Text);
com.Parameters.AddWithValue("#Gender", ddlGender.Text);
com.Parameters.AddWithValue("#School", txtSchool.Text);
com.Parameters.AddWithValue("#Grade", txtGrade.Text);
//The following fields are added from the contact information to the corresponding database fields
com.Parameters.AddWithValue("#Address", txtAddress.Text);
com.Parameters.AddWithValue("#APT", txtApt.Text);
com.Parameters.AddWithValue("#City", txtCity.Text);
com.Parameters.AddWithValue("#State", ddlState.Text);
com.Parameters.AddWithValue("#Zip", txtZip.Text);
com.Parameters.AddWithValue("#Email", txtEmail.Text);
com.Parameters.AddWithValue("#Phone", txtPhone.Text);
com.Parameters.AddWithValue("#CellPhone", txtCellPhone.Text);
com.Parameters.AddWithValue("#ParentFName", txtParentFName.Text);
com.Parameters.AddWithValue("#ParentLName", txtParentLName.Text);
com.Parameters.AddWithValue("#ParentEmail", txtParentEmail.Text);
com.ExecuteNonQuery();
con.Close();
//End database connection
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Student has been successfully added!')", true);
}
}

using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
// Add your #Fname and #LName parameters here
com.Parameters.AddWithValue("#FName", firstName);
com.Parameters.AddWithValue("#LName", lastName);
con.Open();
using (OleDbDataReader myReader = com.ExecuteReader())
{
myReader.Read();
int count = myReader.GetInt32(0);
// return count > 0 or whatever to indicate that it exists
}
}

couple of things:
you can set in your table the first name and last name as 1 primary key (yes it possible in ms-access). this way you will NEVER get any duplicate records
count(*) is not the best practice with databases.. but since you are dealing with ms-access
using (OleDbDataReader myReader = com.ExecuteReader())
{
// reads the first and only column count(*) and convert it to a number
if (Convert.ToInt16(myReader[0]) > 0)
{
// an entry already exists
}
}

You should use ExecuteScalar when the return value of your query is only a single row with a single column. Of course the OleDbCommand that has parameters placeholders in its command text needs to have also a corresponding Parameters collection
using (OleDbConnection con = new OleDbConnection(constr))
using (OleDbCommand com = new OleDbCommand("SELECT COUNT(*) FROM StudentList WHERE [FName] = #FName AND [LName] = #LName", con))
{
con.Open();
com.Parameters.AddWithValue("#FName", txtFirstName.Text);
com.Parameters.AddWithValue("#LName", txtLastName.Text);
int count = Convert.ToInt32(com.ExecuteScalar());
if(count == 0)
{
... record doesn't exist
}
else
{
... you have got count records
}
}
However let me say that this logic is rather weak. What happen if two students have the same First and Last name? What happen if someone mistype the name?. I think that you should require something more unique. Like a SSN or another ID provided by your school. (A Student Number or something alike)

if (txtYear.Text != "")
{
cmd = new SqlCommand("Select YearName from Year where YearName='" + txtYear.Text + "'", ConnOpen());
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
int i = ds.Tables[0].Rows.Count;
if (i > 0)
{
MessageBox.Show("Duplicate Values are not valid!!!");
}
else
{
if (Classes.ClassDatabaseConnection.UserMessage("Are you srue you want to Add this Year!!!", "Confirm Updation") == true)
{
string insert = "insert into Year(YearName) values('" + txtYear.Text + "')";
int result = sqlrep.ExecuteNonQuery(insert);
if (result > 0)
{
System.Windows.Forms.MessageBox.Show("Year Added Successfully.", "Information", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
}
}
dataLoad();
}
}

Related

C# & ASP.NET : SqlCommand won't insert record but preserving autoincrement id

I'm writing a SQL command to insert new record into a SQL Server database using an ASP.NET website, but it's not working, although it's preserving the id of an auto-increment column.
When the auto-increment value is 5, and then I try to insert a new row using Management Studio, it does insert the record with id=7.
Thanks to anyone who tells me what I'm doing wrong here
Here is the code:
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
try
{
cmd.CommandText = "insert into Bill values (#car, #date, #client, #speedometer, #employee, #notes)";
cmd.Parameters.AddWithValue("#car", carid);
cmd.Parameters.AddWithValue("#date", txt_bill_date.Value);
cmd.Parameters.AddWithValue("#client", cmb_client_name.Value);
cmd.Parameters.AddWithValue("#speedometer", txt_car_gas.Value);
cmd.Parameters.AddWithValue("#employee", cmb_emp.Value);
cmd.Parameters.AddWithValue("#notes", txt_notes.Value);
cmd.ExecuteNonQuery();
cmd.CommandText = "select top 1 bill_id from Bill order by bill_id DESC";
DataTable inserted = new DataTable();
sda.Fill(inserted);
if (inserted.Rows.Count > 0)
{
billid = inserted.Rows[0]["bill_id"].ToString();
contractid.Values["id"] = inserted.Rows[0]["bill_id"].ToString();
Response.Redirect("BillContracts.aspx");
}
}
catch(Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "swal('خطأ', '" + ex.Message + "', 'error')", true);
}
Sorry for the inconvenience guys
your advice of putting a break point on the catch saved my day
the problem was with the columns type
apparently be mistake i added an int column for a string value
i apologize again if i didn't do this right

Prevent over booking ticket by using busno and date

Am working on small project and am new to coding, i want the system to be a booking system whenever specific bus is booked for specific date then that bus will be specific to that date. for example Bus12 is booked to be used on 21 of Aug then if by mistake the admin tries to book the same bus for something else prevent that booking based on checking the date and busno. am simply using web forms, below is my database table and behind code.please help me am not getting any error nothing is stored in my database table when i refresh it.i want if the entered date and Busno is same as the one in table then prevent booking.
protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["MyDatabase1ConnectionString"].ConnectionString;
tbDate.Text = Calendar1.SelectedDate.ToShortDateString();
using (SqlConnection con = new SqlConnection(cs))
{
string check = "SELECT BusNo, Date FROM Ticket WHERE (BusNo = #busno) AND(Date = #NewDate))";
SqlCommand cmd = new SqlCommand(check, con);
cmd.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd.Parameters.AddWithValue("#NewDate", DateTime.Parse(tbDate.Text));
con.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (#busno ,#date , #time , #bickup , #dropoff ,#fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("#date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("#time", tbTime.Text);
cmd2.Parameters.AddWithValue("#dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("#bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("#fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}
}
}
}
Can try removing the while (rdr.Read()) portion ?
So your code will be
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
Response.Write("double booking");
}
else
{
string insertQuery = "INSERT INTO Ticket (BusNo, Date, Time,Bickup,DropOff,Fare) VALUES (#busno ,#date , #time , #bickup , #dropoff ,#fare )";
SqlCommand cmd2 = new SqlCommand(insertQuery, con);
cmd2.Parameters.AddWithValue("#busno", tbBusno.Text);
cmd2.Parameters.AddWithValue("#date", DateTime.Parse(tbDate.Text));
cmd2.Parameters.AddWithValue("#time", tbTime.Text);
cmd2.Parameters.AddWithValue("#dropoff", tbDrop.Text);
cmd2.Parameters.AddWithValue("#bickup", tbBickup.Text);
cmd2.Parameters.AddWithValue("#fare", int.Parse(tbfare.Text));
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
}

Trying to insert int variable into SQL Server table

protected void addItem_Click(object sender, EventArgs e)
{
String CS = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
string PID;
Button oButton = (Button)sender;
PID = oButton.CommandArgument.ToString();
int productId = Convert.ToInt32(PID);
Debug.Write(productId);
string email = (string)(Session["email"]);
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
When my query executes, I get an error
Invalid column name 'productId'
As you can see, I have converted a string into an integer variable, I have printed off the variable to check what it is returning. It does return a int as expected, but for some odd reason i can not insert into to my table. Any help would be great.
Hope productId is not the primary key of the basket table.
Then,instead of
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( productId,'" + email + "')", con);
Modify like below
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values( #productId,#email)", con);
cmd.Parameters.Add(new SqlParameter("#productId",productId );
cmd.Parameters.Add(new SqlParameter("#email",email );
Why suggested to modify is to avoid SQLInjection attack. If you are unaware about that please go through the below link and learn it
https://en.wikipedia.org/wiki/SQL_injection
Two issues here, number 1, and a big one, parameterize that query! You're opening yourself up to SQL injection attacks with code like that.
The second is that you're not actually passing in your productId variable, you're telling it to use the value for the productId column - which is also the column you're trying to insert into.
SqlCommand cmd = new SqlCommand("insert into basket (productId, email) values (#productId, #email)");
cmd.Parameters.AddWithValue("#productId", productId);
cmd.Parameters.AddWithValue("#email", email);
I can't stress enough how dangerous it is to dump user input into SQL that's going to be run directly on your database.

Exporting Data into Access using C# simultaneously into two tables

I'm trying to enter the id, first and last name into a table and then according to a combo box input I create another record right after that saves id of the student and the id of the Team which was chosen bu the combo box. Here is my code. everything runs well the only problem is that after that the record in the TeamPlayers table is not added. Please anyone ?!?
try
{
string team = null;
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO Students(BaruchID, FirstName, LastName) VALUES(#id, #first, #last)", conn);
conn.Open();
comm.Parameters.AddWithValue("#id", tbBaruchID.Text);
comm.Parameters.AddWithValue("#id", FirstName.Text);
comm.Parameters.AddWithValue("#id", LastName.Text);
comm.ExecuteNonQuery();
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("SELECT TeamNum FROM Teams WHERE TeamName='" + cbTeam.Text +"'", conn);
conn.Open();
OleDbDataReader dr = comm.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
team = dr["TeamNum"].ToString();
}
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO TeamPlayers(ID, BaruchID, TeamID) VALUES(#i, #id, #teamid)", conn);
conn.Open();
comm.Parameters.AddWithValue("#i", 1);
comm.Parameters.AddWithValue("#id", tbBaruchID.Text);
comm.Parameters.AddWithValue("#teamid", int.Parse(team));
conn.Close();
}
MessageBox.Show("Student Added for team"+ cbTeam.Text);
}
The parameter names in the first INSERT statement are not used when adding the parameter values. All the comm.Parameters.AddWithValue("#id", .....); lines use #id. Therefore, the actual id value is never saved to table student.
The second INSERT has always uses 1 as the value of 'id'. Assuming that 'id' is a primary key, it can only contain unique values. Make the 'id' field an IDENTITY field and then remove it from the INSERT statement. Each time a record is then added to the table it will be given the next number in an ever incrementing sequence.
Corrected Code: http://dotnetfiddle.net/Dr9842

How to check if a value already exists in my database and show a validation message

I have the below code, that connects to a Sql database and insert's data into a table :
string firstNameV = txtFname.Text;
string surnameV = txtSname.Text;
string emailV = txtEmail.Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)";
cmd.Parameters.Add("#Title", SqlDbType.NVarChar).Value = title;
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = firstNameV;
cmd.Parameters.Add("#Surname", SqlDbType.NVarChar).Value = surnameV;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = emailV;
cmd.Parameters.Add("#EstablishmentType", SqlDbType.NVarChar).Value = eType;
cmd.Parameters.Add("#Interests", SqlDbType.NVarChar).Value = ins;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
How do I check if an email being entered in the "txtEmail" text box already exists in my database, in the email column and then alert message saying email already exists so it doesn't get inserted into my database?
Call this method in required textbox or area
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Try this
cmd.CommandText = "IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email = '"
+ txtEmail.Text + "')
BEGIN
INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)
END";
Call a stored Procedure and inside the stored procedure you can check
before insert
IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email =#email)
Begin
insert query here
end
In another way you can check it in text changed event also
Create a procedure on SQL server and check whether the name exists or not
CREATE PROCEDURE Procedure_Name
#mystring varchar(100),
#isExist bit out
AS
BEGIN
if exists(select column1 from tblTable1 where column1=#mystring)
begin
select #isExist=1
end
else
begin
select #isExist=0
end
END
GO
This is a sample procedure. If #isExist=1 that means the value exist.otherwise not. create a method to call this procedure and go on...
Happy Coding
This works for me:
Create a function Called CheckMail(string email)
public bool CheckMail(string email)
{
SqlConnection con = new SqlConnection("Data Source=*******; Initial Catalog=Your Database Name; Persist Security Info=True;User ID=****; Password=******");
SqlCommand cmd = new SqlCommand("select email from Table Name where email='"+email+ "'",con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
return false;
}
else
{
return true;
}
}
Then Implement in Button Click as
Pass Textbox value in function that were created..
if (CheckMail(EmailTxt.Text))
{
Write Your insert code to database
}
else
{
Error Message or Alert to Show Already Exists in database
}

Categories