Question: data gets duplicated when inserting into database. How do I not make duplicate entries in database?
I read about securing/ preventing SQL injection by not using the
texboxt1.text
So I tried using
parameters.add()
But the entries are duplicated for every insertion.
This is the image of the database...
This is my code
protected void Button1_Click(object sender, EventArgs e)
{
string username = txtuser.Text;
string firstname = txtfirst.Text;
string lastname = txtlast.Text;
string email = txtemail.Text;
string password = txtpass.Text;
string gender = rbgender.Text;
string nationality = ddcountry.Text;
string Connect_string = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlConnection Connect = new SqlConnection(Connect_string);
Connect.Open();
string pass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
SqlCommand Command = new SqlCommand("INSERT INTO [Users] (username, firstname, lastname, email, password, gender, nationality) VALUES (#username, #firstname, #lastname, #email, #password, #gender, #nationality)", Connect);
Command.Parameters.AddWithValue("#username", username);
Command.Parameters.AddWithValue("#firstname", firstname);
Command.Parameters.AddWithValue("#lastname", lastname);
Command.Parameters.AddWithValue("#email", email);
Command.Parameters.AddWithValue("#password", pass);
Command.Parameters.AddWithValue("#gender", gender);
Command.Parameters.AddWithValue("#nationality", nationality);
Command.ExecuteNonQuery();
int success = Command.ExecuteNonQuery();
if (success > 0)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
Label1.Visible = true;
Label1.Text = "You have successfully registered";
Connect.Close();
}
else
{
Label1.Text = "Your information has not been entered to database";
Connect.Close();
}
When I use
INSERT INTO Table () VALUE '"+textbox1.text +"'
it doesn't get duplicated but yeah, SQL injection-thingy.
You have two calls to the ExecuteNonQuery which actually fires the command:
Command.Parameters.AddWithValue("#nationality", nationality);
Command.ExecuteNonQuery(); //CALLED HERE First Time
int success = Command.ExecuteNonQuery(); //CALLED HERE Second Time (This is the one you want)
if (success > 0)
{
Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
Label1.Visible = true;
Label1.Text = "You have successfully registered";
Connect.Close();
}
You are executing the query twice, by these lines:
Command.ExecuteNonQuery();
int success = Command.ExecuteNonQuery();
Remove the first Command.ExecuteNonQuery() and leave the second one with the int success.
Related
The error I'm getting is pointing to when I call
cmd.BeginTransaction(IsolationLevel iso);
error description click here
This method is called the the user tries to sign up on log in webpage. If HTML5 client-side input verification is accepted and both password fields match, this method is called and empty textboxes are filled with a space (" ").
This is for my senior project, please help.
//this method adds a record to the table customers
public Boolean addUser(String email, String password, String name, String phone, String company, String address, String city, String state, String zip)
{
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand cmd = conn.CreateCommand();
MySqlTransaction trans = conn.BeginTransaction(IsolationLevel.Serializable);
cmd.Connection = conn;
cmd.Transaction = trans;
try {
conn.Open();
//these are the mandatory fields to be inserted)
string sql = "Insert into customers(name,password,phone,email) values (?name,?password,?phone,?email)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?name", name);
cmd.Parameters.AddWithValue("?email", email);
cmd.Parameters.AddWithValue("?phone", phone);
cmd.Parameters.AddWithValue("?password", password);
cmd.ExecuteNonQuery();
trans.Commit();
conn.Close();
conn = new MySqlConnection(connString);
cmd = conn.CreateCommand();
cmd.Connection = conn;
//these fields are optional and if input is empty they are being passed as " "
sql = "Update customers Set username = ?company, address=?address ,city=?city, state=?state, zipcode=?zip where customerID=MAX(customerID)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("?company", company);
cmd.Parameters.AddWithValue("?address", address);
cmd.Parameters.AddWithValue("?city", city);
cmd.Parameters.AddWithValue("?state", state);
cmd.Parameters.AddWithValue("?zip", zip);
cmd.ExecuteNonQuery();
conn.Close();
}
catch (MySqlException ex)
{
trans.Rollback();
errorcode = ex.Number;
MessageBox.Show("7. Sign Up Failure\nError code: " + getError(), "Sign Up failure", MessageBoxButtons.OK, MessageBoxIcon.Error);
conn.Close();
return false;
}
return true;
}
Update:
IF I don't include the transaction methods, the error i'll get is when I perform the second database transaction (cmd.ExecuteNonQuery())
See error picture
It would be nice to implement the IsolationLEvel Serializable since it stops other Database transactions from occurring at the same time. But at this point I'm just trying to get users to sign up.
So I'm trying to insert text from textbox and combobox controls into an SQLite database, but i am getting a syntax error
private void btnConfirm_Click(object sender, EventArgs e)
{
int indexID = 0;
string username = txtUsername.Text;
string password = txtPassword.Text;
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
int age = cmbAge.SelectedIndex + 1;
string country = cmbCountry.Text;
string city = txtCity.Text;
string address = txtAddress.Text;
string breeds = txtBreeds.Text;
string notes = "None";
SQLiteConnection registerConnection = new SQLiteConnection("Data Source=|DataDirectory|/Resources/database.sqlite;Version=3;");
registerConnection.Open();
SQLiteCommand registerCommand = new SQLiteCommand("INSERT INTO users (indexID,username,password,firstname,lastname,age,country,city,address,tigerbreeds,notes)", registerConnection);
registerCommand.Parameters.AddWithValue("indexID", indexID); //0 for now, but we're going to change this later.
registerCommand.Parameters.AddWithValue("username", username);
registerCommand.Parameters.AddWithValue("password", password);
registerCommand.Parameters.AddWithValue("firstname", firstName);
registerCommand.Parameters.AddWithValue("lastname", lastName);
registerCommand.Parameters.AddWithValue("age", age);
registerCommand.Parameters.AddWithValue("country", country);
registerCommand.Parameters.AddWithValue("city", city);
registerCommand.Parameters.AddWithValue("address", address);
registerCommand.Parameters.AddWithValue("tigerbreeds", breeds);
registerCommand.Parameters.AddWithValue("tigerbreeds", notes);
registerCommand.ExecuteNonQuery();
}
Does anybody have any idea how to fix this?
An unhandled exception of type 'System.Data.SQLite.SQLiteException' occurred in System.Data.SQLite.dll
Additional information: SQL logic error or missing database
near ")": syntax error
Try updating to this:
SQLiteCommand registerCommand = new SQLiteCommand("INSERT INTO users (indexID,username,password,firstname,lastname,age,country,city,address,tigerbreeds,notes) VALUES (#indexID, #username, #password, #firstname, #lastname, #age, #country, #city, #address, #tigerbreeds, #notes)", registerConnection);
registerCommand.Parameters.AddWithValue("#indexID", indexID); //0 for now, but we're going to change this later.
registerCommand.Parameters.AddWithValue("#username", username);
registerCommand.Parameters.AddWithValue("#password", password);
registerCommand.Parameters.AddWithValue("#firstname", firstName);
registerCommand.Parameters.AddWithValue("#lastname", lastName);
registerCommand.Parameters.AddWithValue("#age", age);
registerCommand.Parameters.AddWithValue("#country", country);
registerCommand.Parameters.AddWithValue("#city", city);
registerCommand.Parameters.AddWithValue("#address", address);
registerCommand.Parameters.AddWithValue("#tigerbreeds", breeds);
registerCommand.Parameters.AddWithValue("#notes", notes);
registerCommand.ExecuteNonQuery();
You must construct a valid SQL query . Insert (columnName) Values (#paramName)
I'm working with ASP.Net web application project . in my Registration form the Username and the Email will be check if it's exist in the database or not. but my problem is if the username and the Email are exist the user can register normally and his data will be added in the database! how i can stop it from adding these data and forced the user to change the username or the Email if one of them is exist ! please any help ?
my .aspx.cs page :
protected void Button1_Click(object sender, EventArgs e)
{
byte[] License;
Stream s = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(s);
License = br.ReadBytes((Int32)s.Length);
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
conn.Open();
string insertQuery = "insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#name", TextBoxName.Text);
com.Parameters.AddWithValue("#username", TextBoxUsername.Text);
com.Parameters.AddWithValue("#password", TextBoxPassword.Text);
com.Parameters.AddWithValue("#email", TextBoxEmail.Text);
com.Parameters.AddWithValue("#phone", TextBoxPhone.Text);
com.Parameters.AddWithValue("#city", DropDownList1.SelectedItem.ToString());
com.Parameters.AddWithValue("#License", License);
com.ExecuteNonQuery();
Response.Write("DONE");
conn.Close();
}
catch (Exception ex)
{ Response.Write("Error:" + ex.ToString()); }
}
protected void TextBoxUsername_TextChanged(object sender, EventArgs e)
{ // to check if the Username if exist
if (!string.IsNullOrEmpty(TextBoxUsername.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", TextBoxUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
checkusername.Visible = false;
}
}
protected void TextBoxEmail_TextChanged(object sender, EventArgs e)
{ // to check if the Email if exist
if (!string.IsNullOrEmpty(TextBoxEmail.Text))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from DeliveryMen where Email=#email", con);
cmd.Parameters.AddWithValue("#Email", TextBoxEmail.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
Div1.Visible = true;
Image1.ImageUrl = "NotAvailable.jpg";
Label2.Text = "the Email Already Taken";
System.Threading.Thread.Sleep(2000);
}
else
{
Div1.Visible = true;
Image1.ImageUrl = "Icon_Available.gif";
Label2.Text = "the Email Available";
System.Threading.Thread.Sleep(2000);
}
}
else
{
Div1.Visible = false;
}
}
Set unique constraints on your Username and email columns, your sql insert will throw an exception and you can handle that and notifiy the client accordingly.
See https://msdn.microsoft.com/en-GB/library/ms190024.aspx
use an insert stored procedure instead of inline insert query and in stored procedure before insert check where this username email id exist or not.
if (not exists(select 1 from DeliveryMen where Username= #Username and Email=#Email))
begin
insert into DeliveryMen (Name,Username,Password,Email,Phone,City,License) values (#name ,#username, #password, #email ,#phone ,#city,#License)
end
The primary key needs to be set in the database itself.
Suppose 'username' is your primary key and therefore unique. Then you can check whether it already exists in the database or not as follows:
private void button2_Click(object sender, EventArgs e
{
conn.Open();
com.Connection = conn;
sql = "SELECT COUNT(*) FROM lapusers WHERE [username] = #username";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
int numRecords = (int)com.ExecuteScalar();
if (numrecords == 0)
{
sql = "INSERT INTO lapusers([username],[fillingcode],[branch],[department],[agency])VALUES(#username,#fillingcode,#branch,#department,#agency)";
com.CommandText = sql;
com.Parameters.Clear();
com.Parameters.AddWithValue("#username", userlapbox.Text);
com.Parameters.AddWithValue("#fillingcode", userfilllapbox.Text);
com.Parameters.AddWithValue("#branch", comboBox2.Text);
com.Parameters.AddWithValue("#department", comboBox1.Text);
com.Parameters.AddWithValue("#agency", comboBox3.Text);
com.ExecuteNonQuery();
MessageBox.Show("Created Successfully ..");
}
else
{
MessageBox.Show("A record with a user name of {0} already exists", userlapbox.Text);
}
conn.Close();
}
I've written this registration form which adds data to my SQL Server database. What I want is an exception when the user enters a username that is already in the database.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn2.Open();
string CheckUser = "select Username from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
com2.ExecuteNonQuery();
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
conn2.Close();
if (IsMatch == 0)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string InsertQuery = "insert into UserData (Username, Email, Password, Country) values (#Username, #Email, #Password, #Country)";
SqlCommand com = new SqlCommand(InsertQuery, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
conn.Close();
}
else
{
Response.Write("User Already Exists!");
}
}
catch (Exception ex)
{
Response.Write(Convert.ToString(ex));
}
}
When I run it, I get an exception on the following line:
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
Blam's second solution works, but the IsMatch can be simplified a bit by casting to int instead of going to string and parsing.
This should also be handled at the database level. Set a primary key on your username column:
ALTER TABLE UserData ADD CONSTRAINT
PK_UserData PRIMARY KEY CLUSTERED (Username)
If you do it this way, then you don't even have to check for duplicates explicitly, you can just try to create the user and handle the exception if it fails:
try
{
using (var conn = new SqlConnection((ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)))
{
conn.Open();
#if DOUBLE_CHECK
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
if ((int)com2.ExecuteScalar() > 0)
{
Response.Write("User already exists");
return;
}
#endif
string InsertQuerry = "insert into UserData (Username,Email,Password,Country) values (#Username,#Email,#Password,#Country)";
SqlCommand com = new SqlCommand(InsertQuerry, conn);
com.Parameters.AddWithValue("#Username", UsernameTextBox.Text);
com.Parameters.AddWithValue("#Email", EmailTextBox.Text);
com.Parameters.AddWithValue("#Password", PasswordTextBox.Text);
com.Parameters.AddWithValue("#Country", CountryDropDownList.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
}
}
catch (SqlException se)
{
if (se.Errors.OfType<SqlError>().Any(e => e.Number == 2627))
{
Response.Write("User already exists");
}
else
{
Response.Write(se.ToString());
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
If you handle the exception this way, the #if DOUBLE_CHECK section is redundant and can be removed. An attempt to add duplicate name will cause a SQL error and exception, and this will detect and handle the "duplicate key" error.
Two unrelated notes on your code:
Response.Redirect() will abort the current thread and your conn.Close() will not be called. Use a using() to ensure it's called.
Storing a password in the database as plain text is a disaster waiting to happen. PLEASE take a look at Best way to store password in database for some ideas about how to do this correctly
That won't return an integer
string CheckUser = "select count(*) from UserData where Username like #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", "'%"+ UsernameTextBox.Text +"%'");
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
And you don't need to use two different connections.
Just use one and close it in a Finally.
string CheckUser = "select count(*) from UserData where Username = #Username";
SqlCommand com2 = new SqlCommand(CheckUser, conn2);
com2.Parameters.AddWithValue("#Username", UsernameTextBox.Text );
int IsMatch = Convert.ToInt32(com2.ExecuteScalar().ToString());
This returns 0 or 1. This should fix your issue. Looks like you need to return an int type. Or you could change it to bool if you want. Either way, this sql statement should help! :)
select
isnull(convert(bit,(select top 1 case
when username != '' then 1
else 0 end
from UserData
where username like #Username)),0)
I'm trying to add values into my database using text boxes.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string MemberID = txtMember.Text;
string FirstName = txtFirstName.Text;
string LastName = txtLastName.Text;
string Phone = txtTelephone.Text;
string Email = txtEmail.Text;
sql = " INSERT INTO A_Member ( MemberID, LastName, FirstName, Phone, Email) VALUES ( #Member, #LastName, #FirstName, #Phone, #Email);";
dbCmd = new OleDbCommand(sql, dbConn);
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
When i try to use the add button it says "no value given for one or more parameters.
is this something within my .cs or .mdb file? or can i change something in this part of the code?
You have correctly used parameters in your SQL code but you haven't then added those parameters to your command, e.g.
dbCmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text);
You must add a parameter to the command for each place-holder that appears in your SQL code.
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
string memberID = txtMember.Text.Trim();
string firstName = txtFirstName.Text.Trim();
string lastName = txtLastName.Text.Trim();
string phone = txtTelephone.Text.Trim();
string email = txtEmail.Text.Trim();
sql = "INSERT INTO A_Member ( MemberID, LastName, FirstName, Phone, Email) VALUES ( #Member, #LastName, #FirstName, #Phone, #Email);";
dbCmd = new OleDbCommand(sql, dbConn);
dbCmd.Parameters.Add("#MemberID",SqlDbType.Int32).Value = Convert.ToInt32(memberID);
dbCmd.Parameters.Add("#LastName",SqlDbType.Varchar,30).Value = lastName;
dbCmd.Parameters.Add("#FirstName",SqlDbType.Varchar,30).Value = firstName;
dbCmd.Parameters.Add("#Phone",SqlDbType.Int32).Value = Convert.ToInt32(phone);
dbCmd.Parameters.Add("#LastName",SqlDbType.Varchar,30).Value = email;
// Execute query
dbCmd.ExecuteNonQuery();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}