Problem with a sql statement - c#

string insertCommand =
"INSERT INTO Users (UserID) VALUES" + "" + "(CONVERT(uniqueidentifier, '" +
UsersIdentityToinsert + "'),'"+ userName+",0,null')";
it tells me:
There are fewer columns in the INSERT statement than values specified
in the VALUES clause. The number of
values in the VALUES clause must match
the number of columns specified in the
INSERT statement.
But i have four columns?

you only have UserID in the insert list but in the value list, you have two values - a uniqueidentifier and a username
this would work better: (assuming the name of your username column)
string insertCommand =
"INSERT INTO Users (UserID, username) VALUES" + "" +
"(CONVERT(uniqueidentifier, '" + UsersIdentityToinsert + "'),'"+ userName+"')";
EDIT:
I feel i need to address this part a bit more clearly:
But i have four columns?
The error you received refers to the number of columns specified in the INSERT statement - not the actual table so if you start an INSERT with:
INSERT INTO AnyTable (ColumnA, ColumnB)
you need to match the number of columns here in your VALUES clause
VALUES ("Value1", "Value2")

You are missing "UserName" in column Names, that is, Column Name and values mismathch.
string insertCommand =
"INSERT INTO Users (UserID,UserName) VALUES" + "" +
"(CONVERT(uniqueidentifier, '" + UsersIdentityToinsert + "'),'"+ userName+"')";

Related

Error using a trigger in c#

I made a Table using a Database in visual 2015 and in the table I have name, n1 , n2 , and avg. I made a insert button with 3 textboxes where I insert my name, number1 and number2 and when I press the button I want to save them in a table. If I use 4 textboxes (one for avg) it works, but I want to use a trigger. So.. I created a trigger >
CREATE TRIGGER [Trigger]
ON [dbo].[Table1]
FOR DELETE, INSERT, UPDATE
AS
BEGIN
UPDATE Table1
SET avg = (N1+N2)/2
END
and here is my insert string
string ins = "insert into Table1 values ('"; ins += textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')";
and I get this error..
Column name or number of supplied values does not match table definition.
I don't know what to do :(
Ok, I still don't think we have all the information, but I'll give a crack at it...
The error message is from the insert statement, not from the trigger.
For your insert, I'd format it so you specifically state which values/columns will be inserted into the table.
It appears as though your average column is a non-nullable field, without a default constraint. So when you try to insert just the 3 values, it wants 4, because it HAS to have 4 (non-nullable). That's why it's throwing the error.
I'd structure your isnert like this:
insert
into Table (Col1, Col2, Col3)
values (val1, val2, val3)
Then, add a default constraint [then updated by trigger], OR, make the Average column nullable, so it can again then be updated via the trigger.
I bet you have a primary key column or another column you're not telling us about.
Either make the Primary Key column Auto-Increment, or make each column allow nulls or give each column a default value.
Also look up SQL Injection as your insert statement is susceptible to attacks.
There is also a problem with your syntax:
string ins = "insert into Table1 values ('"; ins += textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')";
It should be
string ins = "insert into Table1 values ('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "')";

Nested Insert Into Errors

I've created this Insert Into SQL query, it takes information from the table lessons where the text box containing the lesson ID matches with any of the lessons. I have tested this Query works as it returns the correct values to a datagrid view in.
The second part of the query is supposed to get the student ID and Student Name from the text box that the user has input information. Then transfer this into the Less/Stud table.
This table has a the following Columns
Lesson Name Lesson ID Student ID Student Name Optional?
I do not need to worry about the Optional column as that is a check box not needed yet, below is the current query that doesnt work. It returns the following errors:
Incorrect Syntax near '/'
Incorrect Syntax near 'Test Student Name'
The second error within the ' ' always contains the information from the student name text box.
INSERT INTO Less/Stud ([LessonName],[Lesson ID],[Student ID],[Student Name])
SELECT LessonName, LessonID
FROM Lessons
WHERE ClassID ='" + txtClassID.Text + "'
AND (SELECT [Student ID], [StudentName]
'" + txtStuId.Text + "', '" + txtName.Text + "' "
You need to put all four columns being inserted in the outer select:
INSERT INTO Less/Stud ([LessonName],[Lesson ID],[Student ID],[Student Name])
SELECT LessonName, LessonID, '" + txtStuId.Text + "', '" + txtName.Text + "' "
FROM Lessons
WHERE ClassID ='" + txtClassID.Text + "'
There are two errors in your query.
If your table is Less/Stud then you must call the table name with square brackets like [Less/Stud]
Your Insert query have 4 columns but your SELECT query have only 2 columns. Thats also must be changed.
And the most important one, your query is prone to SQL injection. Try to use parameterized query.
Is "Less/Stud" your table name? I would suggest putting that in quotes, because the / seems to be confusing the database.
The WHERE clause also seems to be incomplete. A subselection is being started, but never completed.
You should also only put the fields you actually want to insert data into in the first line. Since you only provide 2 values in the SELECT clause, you can not define 4 fields to insert into.
EDIT: It turns out you want to insert values from a textbox into the Student ID and Student Name fields, based on your clarification. I have altered my suggested query to reflect this. I have not been able to test this, so I might have some mismatching quotes here and there, but I think it should be something like this:
"INSERT INTO [Less/Stud] ([LessonName],[Lesson ID],[Student ID],[StudentName])
SELECT LessonName
, LessonID
, '" + txtStuId.Text + "'
, '" + txtName.Text + "'
FROM Lessons
WHERE ClassID ='" + txtClassID.Text + "' "
You might want to consider using the String.Format() method to put the textbox values into the SQL string though. I personally think the string would be more readable that way. It would look like this:
var yourQuery = String.Format(
"INSERT INTO [Less/Stud] ([LessonName],[Lesson ID],[Student ID],[StudentName]) SELECT LessonName, LessonID, '{0}', '{1}' FROM Lessons WHERE ClassID ='{2}' "
, txtStuId.Text
, txtName.Text
, txtClassId.Text
);
Breaking up the SQL statement itself into multiple lines might also be a good idea, especially for even longer and/or more complicated statements.

String or binary data would be truncated. SQL Statements in C#

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=; Database=; User id=; password=";
conn.Open();
string Query = "Insert into [Capstone0480].[dbo].[NAME] (NameID, FirstName, MI, LastName, UserID) Values('" + this.txtNameID.Text + "','" + txtFirst.Text + "','" + txtMI.Text + "','" + txtLast.Text + "', '" + txtUserID.Text + "')";
SqlCommand createCommand = new SqlCommand(Query, conn);
createCommand.ExecuteNonQuery();
MessageBox.Show("Updated");
conn.Close();
I have been getting this error on the ExecuteNonQuery() statement. I am not sure what is wrong here. I feel as if my sql statements are correct. I am just trying to add what is typed into textboxes into my database.
If there is a better way of doing this or if there is something wrong, please let me know!
One of the columns in your NAME table is shorter than the values you are trying to insert into it.
Try trimming the length of your name textboxes before you insert them into the database, or alternatively increase the length of your database columns.
For example:
If your FirstName Column is varchar(20)
then:
var firstName = txtFirst.Text.Length > 20 ? txtFirst.Text.Substring(0,20) : txtFirst.Text;
then insert the value of firstName into your SQL statement.
In addition, you should set the max length of your Textbox to be no more than the size of your columns.
The error suggest, that your input data length is more than the column length you define in database table.
suppose the column is like
TableName1
ColumnName1 varchar(50)
and now when you want to insert 51 or more character length input string, at that time the Sqlserver gives error. check this sample example.
declare #t table (name varchar(5))
insert into #t values('abc')
select * from #t
insert into #t values('abcdefg') --this gives error as you insert more than define length.
Please check at run-time what is the input string.
Good if you restrict your textbox to insert only the database column length like
<input type="textbox" maxlength="50" />

Insert SQL Values Into a Database Table

I am getting the following error
syntax not correct near item number
but I don't see anything wrong, the values being inserted are from a dataset containing field names in variables from another sql query that is being looped through and then inserted into another table like so....
string strOrderDetails =
"INSERT INTO Orders (Order Number, Item Number, Description, Price) " +
"VALUES ('" + strOrderNo.Replace("'", "''").ToString() + "', '"
+ intItemNo + "', '"
+ strDesc.Replace("'", "''").ToString() + "', '"
+ decPrice + "')";
On execution of the above is where the code falls over and states there's an error near the word item number?
Do I need to do something to the intItemNo as it's an integer?
When a column contains spaces you need to enclose it in square brackets or other delimiter for the choosen database
But said that, please do not use string concatenation to build sql commands, but always a parameterized query.
string strOrderDetails = "INSERT INTO Orders ([Order Number], [Item Number]," +
"Description, Price) VALUES (#ordNum, #temNo, #desc, #price";
using(SqlConnection cn = new SqlConnection(conString))
using(SqlCommand cmd = new SqlCommand(strOrderDetails, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ordNum",strOrderNo);
cmd.Parameters.AddWithValue("#itemNo",intItemNo);
cmd.Parameters.AddWithValue("#desc",strDesc);
cmd.Parameters.AddWithValue("#price", decPrice);
cmd.ExecuteNonQuery();
}
As you could notice, using parameters remove the need to write code to handle quotes in the input values, but also remove the possibility of Sql Injection attacks

I have inserted a row, I want to get it's ID and plus it with an int and insert in that row

I have inserted a row into my table, and I want to get it's ID and plus it with an int and inserted in that row.
But I don't know how to get it's ID.
Here is the insert code:
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO Moin " +
" (Title, TotalID, Code ) " +
"VALUES (#Title , #TotalID, #Code )";
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO Moin " +
" (Title, TotalID, Code ) " +
"VALUES (#Title , #TotalID, #Code ) SELECT SCOPE_IDENTITY()";
object id = objCommand.ExecuteScalar();
Try using the OUTPUT clause of SQL Server in your query - it can return any of the just inserted value (here I'm assuming your column is called ID - adapt as needed):
objCommand.Connection = objConnection;
objCommand.CommandText = "INSERT INTO Moin(Title, TotalID, Code ) " +
"OUTPUT Inserted.ID " +
"VALUES (#Title , #TotalID, #Code ); "
and then execute it like this:
int result = (int)objCommand.ExecuteScalar();
Since you're returning just one row and one column (just the INT), you can use .ExecuteScalar() to retrieve that value back from the INSERT statement.
With the OUTPUT clause, you can return any values just inserted - not just the identity column. So you could also return values that are filled by the database with default values, or whatever you need. If you return multiple values, you need to use a data reader to read them all - ExecuteScalar() only works for a single value.
But, as Anders correctly mentioned - using an ORM like Entity Framework would do all of this automatically for you and you wouldn't have to deal with those raw SQL commands anymore....
Building SQL commands in strings should be considered a legacy technique. If you use Entity Framework or linq-to-sql the retrieval of the id is handled automatically for you.
With pure SQL, use the SCOPE_IDENTITY() function to retrieve the id of the inserted element.

Categories