Prevent inserting duplicate values in Database - c#

How can I prevent duplicate data inserting in database?
What I like is when click button save it will show message "Cannot Insert Duplicate Value". I'm using MSAcess for my database.
Code:
connection1.Open();
OleDbCommand cmd = connection1.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Taxation (ShoesBrand, ShoesCode, ShoesColor) Values (ShoesBrand, ShoesCode, ShoesColor)";
cmd.Parameters.AddWithValue("ShoesBrand", textBox1.Text);
cmd.Parameters.AddWithValue("ShoesCode", textBox2.Text);
cmd.Parameters.AddWithValue("ShoesColor", textBox3.Text);
cmd.ExecuteNonQuery();
connection1.Close();
How do I prevent not to insert same value? Or how can i add to throw exemption when values are the same in database.

You have to create a unique index on the required column of the table. in this way, It will not allow you to insert duplicate records from C# code.
You can learn more about Unique constraints here.
Few points to be noted here. you should use using when initializing the connection. and please read about SQL injections.

Related

C# invalid column name problem but is different from others

Hello i have a table called Card_tbl with a cell CardID. The problem is that when i insert only numbers like 12345 they are uploaded in the database, but when i use mix letters like Q1234R it will say INVALID COLUMN NAME Q1234R I tried many things to fix it but no success.
THE CELL IS ON VARCHAR(50) this is my code
Con.Open();
SqlCommand cmd = new SqlCommand("insert into Card_tbl values(" +txtCardNumber.Text+")", Con);
cmd.ExecuteNonQuery();
MessageBox.Show("Admin Successfully Added!");
Con.Close();
populate();
//updateroomstate();
Clean();
the error is shown here cmd.ExecuteNonQuery();
Thank you in advance.
Solution
The correct solution is to use prepared statements. You've said the column is a varchar(50) so:
using (SqlConnection conn = new SqlConnection("yourconnectionstring"))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("INSERT INTO Card_tbl VALUES (#cardNumber)", conn))
{
// we specify type VarChar and size 50, because your column is a varchar(50)
cmd.Parameters.Add("#cardNumber", SqlDbType.VarChar, 50).Value = txtCardNumber.Text;
cmd.ExecuteNonQuery();
}
}
I would also recommend that you specify the column name for the insert:
INSERT INTO Card_tbl (CardId) VALUES (#cardNumber) -- I've assumed that the column is called CardId
Why do we need parameterized queries / prepared statements?
The reason we need prepared statements is because the user could enter something malicious in the query, forcing your server to execute queries that you didn't intend.
If you have a query like this, SQL Server will do the insert and then drop the table:
INSERT INTO MyTable VALUES ('hello'); DROP TABLE MyTable; -- comment
This is a multi-statement query, meaning that the INSERT will be done first, and then the DROP TABLE will be executed. The -- denotes a comment, and everything after that in the query is discarded.
Now, if you build a query like "INSERT INTO MyTable VALUES ('" + someUserInput + "')", how could a malicious user make this query more like the previous one? Simple: enter SQL into their input.
Suppose someUserInput is '); DROP TABLE MyTable; -- comment then your query will become:
INSERT INTO MyTable VALUES(''); DROP TABLE MyTable; -- comment')
Like this, a malicious user can perform an extremely destructive operation on your database, bypass login pages, expose secret information, etc. This is a huge risk for your application.
Prepared statements work by separating the query text from the parameter values. Because they're not part of the query, they can't be interpreted as SQL. It also means that binary data types can be sent to the server as binary rather than as text. Example: DateTime.
Try this instead
Insert into Card_tbl(CardID) values('" +txtCardNumber.Text+"')"
https://www.w3schools.com/sql/sql_insert.asp

INSERT command for auto increment field in access from asp.net website

I've got my primary key set to auto increment in my access database.
How do I specify that I want the primary key to have the next available value?
e.g.
OleDbCommand cmd = new OleDbCommand("INSERT into Table VALUES (?,"string","string");", conn);
thanks!
If it is set to auto increment you dont have to specify a value for it
just do
OleDbCommand cmd = new OleDbCommand("INSERT into Table VALUES ("string","string");", conn);
although one would prefer you write the column names explicitly
If you have a table as such:
Table
ID SomeString SomeString2
where ID is the primary key, then you'd not need to specify the value for the primary key. It would be "auto-incremented" as you have specified that.
So you'd enter:
OleDbCommand cmd = new OleDbCommand("INSERT into Table (SomeString, SomeString2) VALUES ('stringA','stringB')", conn);
Note: Its a good practice to always mention the column names when performing insertion of records.
Hope this helps!!!
If the database field is already set to auto-incremente, then you don't need to worry about it!
Just insert the other fields!
INSERT into Table VALUES ("string","string")
You can just skip it:
OleDbCommand cmd = new OleDbCommand("INSERT into Table VALUES ("string","string");", conn);

Getting error message when trying to execute code [duplicate]

This question already has answers here:
Column name or number of supplied values does not match table definition
(16 answers)
Closed 9 years ago.
con.Open();
string qry="insert into reg1 values ('"+txtname.Text+"','"+txtaddress.Text+"','"+txtpin.Text+"','"+txtage.Text+"','"+txtgender.Text+"','"+txtcourse.Text+"','"+txtcollege.Text+"','"+txtfname.Text+"','"+txtoccup.Text+"','"+txtmname.Text+"','"+txtskills.Text+"','"+txtmobile.Text+"','"+txtemail.Text+"')";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.ExecuteNonQuery();
con.Close();
I am receiving the following error message when I try to execute this code:
Column name or number of supplied values does not match table definition.
Can anyone help me find the error?
Sounds like your column numbers in your table and your SqlCommand does not match. But since we didn't know anything about your table design, we never know..
If your INSERT command and your table doesn't have the same column number, you have to declare your column names which you want to insert these values..
I count 14 columns on your table from your comment, but you try to add 13 values. These are doesn't match.
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
con.Open();
string qry = #"insert into reg1
values(#name, #address, #pin, #age, #gender, #course, #college, #fname
#occup, #mname, #skills, #mobile, #email)";
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#address", txtaddress.Text);,
.....
cmd.ExecuteNonQuery();
con.Close();
you entered to much or to few values into the table in other words your table has 5 columns and you entered 6 values or 4 check that the values you entered corresponds with your table
best advice i can give is always use a procedure it is recommended to protect against sql injection and it will reduce the chance of this happening ,it is also a lot more efficient than hard coding it from c# end
create a proc and just call it from c# end done ;)
SQL Server stored procedure beginner's guide
create proc example_insert
#values varchar(100) <--- declare parameters
as
insert into [Table]([Column],[Column],[Column])
values('','','',)<--- -this should be the same number as your columns
calling the stored procedure this is in vb but the principle is the same
s1.Open() 'opens the connection
Dim cmd As New SqlCommand("example_insert", s1)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#Value", textbox.Text)<--- a lot simpler

SQL Delete and Update didn't delete and update

I wrote a set of codes using SQL command to delete and update Access records through a C# program. Here is the set of codes:
Update
OleDbCommand cmd = new OleDbCommand("UPDATE Available SET Status = 'AVAILABLE' WHERE AvailableID = ?", cnn);
cmd.Parameters.Add(new OleDbParameter { Value = id.AvailableID });
cmd.CommandType = CommandType.Text;
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
Delete
OleDbCommand cmd = new OleDbCommand("DELETE FROM Log WHERE LogID = ?", cnn);
cmd.Parameters.Add(new OleDbParameter { Value = l.LogID });
cmd.CommandType = CommandType.Text;
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
The program is executable. When I'm trying to delete and update records, the updating record has not been updated and the deleting record still exists.
Pressing the delete button will delete a record in log and updates the product into 'available'. However, the status didn't change and the record didn't delete.
Am I missing something? I always refresh when every transaction has been made.
That is strange. Here are my recommendations:
Verify that you are not accidentally swallowing an error somewhere. You can do this by stepping through the code and verifying that it doesn't jump to a catch handler. Bear in mind this may be somewhere else far away from the location of the code you posted. Just depends on how it's been set up.
Verify that the parameters are the correct values by hard coding the entire query with the LogID as well. Though it's better to use them, parameters sometimes behave in ways you wouldn't expect. It's been some time since I've used dynamic SQL but off the top of my head I don't see anything wrong with your code.
As an aside, I would recommend making the switch to an ORM. Dynamic SQL is very difficult to manage in larger projects and hence it's better to get comfortable with it even when your project is small. It also takes care of any syntactical differences that might exist should you ever port the application to use a MSSQL database in the future. Personally I recommend nHibernate.

Getting error while store data in sql server 2005 through textbox

I am storing data (approx. 1500 words) in SQL server 2005 through textbox and button. I am using this code.
protected void Button1_Click(object sender, EventArgs e)
{
conn.Open();
String query = String.Format("insert into try (data,sno) values ('{0}',22)",TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
cmd.ExecuteNonQuery();
Label1.Text = "submitted";
conn.Close();
}
I have column 'data' of data type 'char(4000)'.
Problem is that, when I store 1st paragraph (approx 1500 words), it stored successfully. But when I stored another paragraph (approx 1500 words), it show me the error.
"Incorrect syntax near 's'. Unclosed quotation mark after the
character string ',22)'."
What is the problem ??
Use Parameters
String query = "insert into try (data,sno) values (#data,22)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("#data", TextBox1.text);
cmd.ExecuteNonQuery();
In this way you don't need to worry about the presence of single quotes in your text and, the most important thing, you avoid SqlInjection Attacks
String.Format will not escape the input string suitably for use in an SQL statement, which will lead to errors & serious vulnerabilities.
You should use Parameterized Queries which are designed specifically to address this.
This sounds like you have an ', or multiple 's, in the TextBox1.Text. You will need to replace all single quotes for double.
String query = String.Format("insert into try (data,sno) values ('{0}',22)",Replace(TextBox1.Text,"'","''"));
However, this approach will open you up to SQL Injection attacks. I'd recommend using a Stored Procedure, like the following:
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "spInsertDataIntoTry";
cmd.Parameters.AddWithValue("#data", TextBox.Text);
cmd.ExecuteNonQuery();
Otherwise, you could use Parameters like others have mentioned.
Does your text contains ' letter? If yes then it is breaking INSERT query.
If you would try to insert following text:
Hello' there
Then your query would look like this:
insert into try (data,sno) values ('Hello' there,22)
Which results in incorrect query.
This is not the way queries should be done, because it leads to security issues (read more: SQL Injection) you should use parametrized queries.
"Incorrect syntax near 's' - this indicates your sql statements is wrong.
i guess that your input content maybe contains sql server keywords, so check your 2nd paragraph is there any keyword such as "'".
for example:
2nd paragraph is: how's the weather? it's cool!!!!!!!
so the sql statement is: insert into try (data,sno) values ('how's the weather? it's cool!!!!!!!',22)
it will arise an exception incorrect syntax near 's'

Categories

Resources