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 + "')";
Related
I am using a foreach loop to access the values of objects(of type Meal) stored in a list. Then I am calling a database query to save these values into the database .
This is the code I'm using :
foreach (Meal ml in mVals)
{
mID = ml.mealID;
MessageBox.Show(Convert.ToString(mID));
string oString2 = " INSERT into [dbo].[OrderMeal] (orderId,mealId,quantity) " + " VALUES ('" + orderId + "','" + mID + "','" + Convert.ToInt32(quant.Text) + "') ;";
SqlCommand oCmd2 = new SqlCommand(oString2, myConnection);
oCmd2.ExecuteNonQuery();
}
However, this only works for the last value in the list. The next loop iteration seems to be doing the same function, thereby saving the same record, giving an
error of violating the primary key constraint .
Is there some error in the way I am looping through the List?
What the structure of OrderMeal table?
Probably you have primary key in your table, and you need to vetify that you don't duplicate him.
try to enter the value in the list from the sql management.
verify that you don't have special characters in each item in the list( like comma and Apostrophe).
I think you can concatenate a set of insert statement and then ExcuteNonQuery for better performance.
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.
I have a table which is needed to be updated from a windows form, i am able to update the displayed values into the table where as i am unable to update a particular column where the value to be updated must be a reference value of the displayed data on windows form. The reference value is in another table. Following is the code:
command.CommandText = "INSERT INTO tblComplaints (ComplaintID, Description,ComplaintTypeID,ReceivedDate,ComplaintTypeID)VALUES('" + TextBox7.Text + "','" + TextBox10.Text + "','" + dateTimePicker1.Text + "',???)";
The question mark(???) within the code is what I require.
To be more precise ComplaintTypeName is being displayed in the form in comboBox1 whereas I require its ID to be updated whose values are present in tblComplaintType
Assuming you assigned the ComboBox values somehow like this in advance
ComboboxItem item = new ComboboxItem();
item.Text = "Item text1";
item.Value = 12;
comboBox1.Items.Add(item);
you could do the following:
command.CommandText = "INSERT INTO tblComplaints " +
"(ComplaintID, Description, ComplaintTypeID, ReceivedDate, ComplaintTypeID) " +
"VALUES (#Description,#ComplaintTypeID,#ReceivedDate,#ComplaintTypeID)";
command.Parameters.AddWithValue("#Description", TextBox7.Text);
command.Parameters.AddWithValue("#ComplaintTypeID", TextBox10.Text);
command.Parameters.AddWithValue("#ReceivedDate", dateTimePicker1.Text);
command.Parameters.AddWithValue("#ComplaintTypeID", comboBox1.SelectedValue);
Note that I stripped the ComplaintID from the sql command. Since this is a INSERT statement, you're likely to get a generated ID for that record. If that's not the case you'll have to provide another parameter in the command.
Additionally you should always parameterize your commands instead of building them via string concatenation to prevent sql injection.
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" />
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+"')";