I want to insert the selected item index from a combobox into a tinyint column (FoodType) in SQL Server. I wrote the code below, but I get an exception:
Must declare the scalar variable #fType
What must I do?
string query = "INSERT INTO MenuTbl (FoodName,FoodType,FoodUnit, SalePrice)" +
"VALUES (#fName, #fType, #fUnit, #fPrice)";
connection = new SqlConnection(conectionString);
SqlCommand cmd = new SqlCommand(query,connection);
cmd.Parameters.AddWithValue("#fName", FNameTextBox.Text.Trim());
cmd.Parameters.AddWithValue("#fTyp", TypeComboBox.SelectedIndex + 1);
cmd.Parameters.AddWithValue("#funit", UnitComboBox.SelectedIndex +1);
cmd.Parameters.AddWithValue("#fprice", int.Parse(PriceEdit.Text));
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
Are you missing an "e" on the parameter?
cmd.Parameters.AddWithValue("#fTyp", TypeComboBox.SelectedIndex + 1);
I think you made a typo with this line of code
cmd.Parameters.AddWithValue("#fTyp", TypeComboBox.SelectedIndex + 1);
It should be #fType atleast according to your select query
string query = "Insert into MenuTbl (FoodName,FoodType,FoodUnit, SalePrice)" +
"VALUES (#fName,#fType,#fUnit, #fPrice)";
And I also think that TypeComboBox.SelectedIndex + 1 will only give you the index+1 numerical value rather than the selected text contents. Is that what you want?
Related
I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
EDIT:
When I run:
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
I get:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
[Edit: added "select" before references to last_insert_id()]
What about running "select last_insert_id();" after your insert?
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
Edit: As duffymo mentioned, you really would be well served using parameterized queries like this.
Edit: Until you switch over to a parameterized version, you might find peace with string.Format:
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Use LastInsertedId.
View my suggestion with example here: http://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
It bothers me to see anybody taking a Date and storing it in a database as a String. Why not have the column type reflect reality?
I'm also surprised to see a SQL query being built up using string concatenation. I'm a Java developer, and I don't know C# at all, but I'd wonder if there wasn't a binding mechanism along the lines of java.sql.PreparedStatement somewhere in the library? It's recommended for guarding against SQL injection attacks. Another benefit is possible performance benefits, because the SQL can be parsed, verified, cached once, and reused.
Actually, the ExecuteScalar method returns the first column of the first row of the DataSet being returned. In your case, you're only doing an Insert, you're not actually querying any data. You need to query the scope_identity() after you're insert (that's the syntax for SQL Server) and then you'll have your answer. See here:
Linkage
EDIT: As Michael Haren pointed out, you mentioned in your tag you're using MySql, use last_insert_id(); instead of scope_identity();
I'm trying to use a while loop to insert into a table from a List. I want to loop through and write each item from the list by it's index. I'm getting an error with the values I'm trying to insert.
"SQL logic error or missing database near "[y]": syntax error"
while (y < Name.Count)
{
cmd.CommandText = "INSERT INTO Mytable(Column1,Column2) values(Column1[y], Column2[y])";
cmd.ExecuteNonQuery();
y++;
}
Your query is not correct. You need to pass parameters to the query:
"INSERT INTO Mytable(Column1,Column2) values(Column1[#Column1], Column2[#Column1])"
command.Parameters.Add( new SqlParameter( "#Column1", y ) );
Having said that, if I were you, I would use Bulk Insert (or something similar) for this and transfer all the data to the database in one trip.
Your parameters, Column1[y] and Column2[y], are not handled as a index to a data structure but rather as plain text.
cmd.CommandText = "INSERT INTO Mytable(Column1,Column2) values(" + Column1[y] + ", " + Column2[y] + ")";
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" />
I am trying to insert data in an SQL table by executing an Insert Query.
The problem is that I need to get the column name from a cell in the selected gridview Row.
Here's the snippet:
SqlCommand cmd30 = new SqlCommand("insert into mytable ( '"+GridView7.SelectedRow.Cells[0].Text+"' , r_id) values ('"+ GridView7.SelectedRow.Cells[1].Text +"', '"+TextBox1.Text+"')",con30);
cmd30.ExecuteNonQuery();
r_id is not a Primary Key.
Error is:
Incorrect syntax near 'r_id'.
Any Help will be appreciated.
Thanks.
Use SqlCommand Parameters.
Also make sure you get valid column name from GridView7.SelectedRow.Cells[0].Text;
Code:
string col1 = GridView7.SelectedRow.Cells[0].Text;
string sql = "INSERT into mytable (" + col1 + ", r_id) Values (#" + col1 + ", #rid)";
SqlCommand cmd30 = new SqlCommand(sql, con30);
cmd30.Parameters.AddWithValue("#" + col1, GridView7.SelectedRow.Cells[1].Text);
cmd30.Parameters.AddWithValue("#rid", TextBox1.Text);
cmd30.ExecuteNonQuery();