Getting error message when trying to execute code [duplicate] - c#

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

Related

Prevent inserting duplicate values in Database

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.

How to insert data to table when one of the columns is set to current timestamp on insert? [duplicate]

This question already has answers here:
Insert query: Column name or number of supplied values does not match table definition
(2 answers)
Closed 7 months ago.
I have a date column of type datetime and I want it to update to the current date and time on every insert.
I set the column to Default Value or Binding = (getdate())
But still, the code itself throws an error about it:
Must declare the scalar variable "#date".
This is the query:
SqlCommand SQLCmd = new SqlCommand("INSERT INTO table VALUES(#name, #phone, #date)", SQLCon);
SQLCmd.Parameters.AddWithValue("#name", name);
SQLCmd.Parameters.AddWithValue("#phone", phone);
I also tried to completely omit #date:
SqlCommand SQLCmd = new SqlCommand("INSERT INTO table VALUES(#name, #phone)", SQLCon);
But then I get this error:
Column name or number of supplied values does not match table definition.
When I changed the id column to identity, it stopped asking me to declare the scalar variable #id, but that didn't help with the date column.
In SQL Server, when you want to insert a row but only fill specific columns, you need to tell which columns:
INSERT INTO table (NAME, PHONE) -- <- tell which columns
VALUES (#name, #phone)
If you don't do this, there is no way it can magically guess what value goes in which column

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

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'

How to create a stored procedure in ADO.NET

I have the following code and i would like it to be a stored procedure.
How do you create and call a stored procedure so that the following code is just like a method call.
Where are stored procedure stored are they created in Visual studio or in MS SQL Server?
using (var conn = new SqlConnection(dbConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText =
#"use [Email Database]
INSERT INTO Emails_Log
(Email_ID, e_To, e_From, e_Subject, e_Date)
VALUES
(#id, #to, #from, #subject, #date)";
// Writes to database (local) instance
cmd.Parameters.AddWithValue("#id", emailID);
cmd.Parameters.AddWithValue("#to", emailTo);
cmd.Parameters.AddWithValue("#from", emailFrom);
cmd.Parameters.AddWithValue("#subject", emailSubject);
cmd.Parameters.AddWithValue("#date", emailSentDate);
cmd.ExecuteNonQuery();
}
NEW QUESTION!
I have managed to Create a Stored Procedure thanks guys, I'm just left with one more Problem.
cmd.CommandType = CommandType.StoredProcedure;
There is a red line under the second CommandType and the error reads
The name 'CommandType' does not exist in the current context
Please help.
On your server Create a procedure using the code below:
CREATE PROCEDURE InsertProc
(
#id <put here the datatype>,
#to <put here the datatype>,
#from <put here the datatype>,
#subject <put here the datatype>,
#date <put here the datatype>
)
AS
INSERT INTO Emails_Log (Email_ID, e_To, e_From, e_Subject, e_Date)
VALUES (#id, #to, #from, #subject, #date)
after you have created the procedure, in your code try this:
// other codes
cmd.CommandText = "InsertProc";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", emailID);
cmd.Parameters.AddWithValue("#to", emailTo);
cmd.Parameters.AddWithValue("#from", emailFrom);
cmd.Parameters.AddWithValue("#subject", emailSubject);
cmd.Parameters.AddWithValue("#date", emailSentDate);
cmd.ExecuteNonQuery();
Most commonly, you would have a sql script (or a series of incremental scripts) that you can apply to your server, creating the objects including things like sprocs; then, just (perhaps in SSMS):
use [Email Database]
create proc SomeNameHere
-- note these lengths are made up
#id int, #to nvarchar(400), #from nvarchar(400),
#subject nvarchar(2000), #date datetime
as
INSERT INTO Emails_Log
(Email_ID, e_To, e_From, e_Subject, e_Date)
VALUES
(#id, #to, #from, #subject, #date)
go
however! I would also say "why make that a sproc?" - unless you have a good reason, I genuinely challenge the thought that everything must be a sproc. In particular, it makes maintenance (especially in a deployment scenario where different servers may be at different stages) harder. Sprocs are good when you want to do non-trivial processing, don't want to transport lots of data over the wire, and it has non-trivial length - but I personally wouldn't use one just for this insert, unless it was strict local policy.
Then, in your command, set the CommandType to be stored procedure, and set "SomeNameHere" as the CommandText.
Stored procedures are stored in sql server. First you have to create the stored procedure in sql server. here you can see how to create a stored procedure. Then you need to call the stored procedure in c# here you can see how you can call stored procedures that are saved in ms sql server. hope it helps.
The error "The name 'CommandType' does not exist in the current context" is caused by a missing namespace. Just add "using System.Data;" on top and it will work.

Categories

Resources