help me please. I don't know what went wrong. It's saying that I have an incorrect syntax near the keyword 'desc' but I don't see anything wrong with this one.
Dim ms As New MemoryStream
pbMainImage.Image.Save(ms, pbMainImage.Image.RawFormat)
Dim sql As String = "insert into contestants(lName,fName,mName,age,gender,address,college,desc,const_num,image_main) values(#lname,#fname,#mname,#age,#gender,#address,#college,#descr,#num,#image)"
Dim cmd As New SqlCommand(sql, constring)
cmd.Parameters.Add("#lname", SqlDbType.VarChar).Value = tbLName.Text
cmd.Parameters.Add("#fname", SqlDbType.VarChar).Value = tbFName.Text
cmd.Parameters.Add("#mname", SqlDbType.VarChar).Value = tbMName.Text
cmd.Parameters.Add("#age", SqlDbType.TinyInt).Value = Convert.ToInt32(tbAge.Text)
cmd.Parameters.Add("#gender", SqlDbType.VarChar).Value = cmbGender.SelectedItem
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = tbAddr.Text
cmd.Parameters.Add("#college", SqlDbType.VarChar).Value = cmbDept.SelectedItem
cmd.Parameters.Add("#descr", SqlDbType.VarChar).Value = tbDesc.Text.Trim()
cmd.Parameters.Add("#num", SqlDbType.TinyInt).Value = Convert.ToInt32(tbNumber.Text)
cmd.Parameters.Add("#image", SqlDbType.Image).Value = ms.ToArray()
OpenConnection()
Try
cmd.Connection = constring
cmd.ExecuteNonQuery()
cmd.Dispose()
constring.Close()
MsgBox("Added New Contestant.")
Catch ex As Exception
MsgBox("Error at " & ex.ToString)
End Try
desc is a reserved keyword - it means "descending" in order by clauses. So: you need to escape that column to [desc] or "desc" (depending on the database) to tell it you mean the column name.
You are using a keyword for a column name so it must be quoted. But, based on your parameter name, you probably meant descr instead of desc, anyway.
Related
it always show an error Incorrect syntax near ')'.
I didnt see any wrong inputs
See my code below
byte[] content = ImageToStream(fName);
cnn.Open();
string sql = "update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id)";
SqlCommand cmd1 = new SqlCommand(sql, cnn);
cmd1.Parameters.AddWithValue("#pic", SqlDbType.Image).Value = content;
cmd1.Parameters.AddWithValue("#fname", SqlDbType.VarChar).Value = txtfirstname.Text;
cmd1.Parameters.AddWithValue("#mname", SqlDbType.VarChar).Value = textBox1.Text;
cmd1.Parameters.AddWithValue("#lname", SqlDbType.VarChar).Value = txtlastname.Text;
cmd1.Parameters.AddWithValue("#position", SqlDbType.VarChar).Value = comboBox2.Text;
cmd1.Parameters.AddWithValue("#startterm", SqlDbType.DateTime).Value = dateTimePicker2.Value.Date;
cmd1.Parameters.AddWithValue("#endterm", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
cmd1.Parameters.AddWithValue("#id", SqlDbType.Int).Value = int.Parse(ID.Text);
cmd1.ExecuteNonQuery();
cnn.Close();
MessageBox.Show("successfully updated");
dataGridView1.DataSource = db.sp_viewofficials();
it should save to sql server my save works
Your update statement has extra ending bracket which is not needed.
"update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id"
I'm trying to connect my SQL Server with ASP.NET, and when I run my insert function, it displays an error.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into Table1 values('"+firstname.Text+"','"+lastname.Text+"','"+city.Text+"')";
cmd.ExecuteNonQuery();
firstname.Text = "";
lastname.Text = "";
city.Text = "";
I expect to show the inserted values but it displays this error:
System.Data.SqlClient.SqlException: 'Column name or number of supplied values does not match table definition.'
Where Id is auto incremented.
You need urgently research about SQL injection, and STOP USING string concatenation for building your SQL insert statement RIGHT NOW.
You need to use the proper technique - parametrized queries -- always - NO exceptions!
And also, it's a commonly accepted Best Practice to list the columns in your INSERT statement, to avoid trouble when tables change their columns (read more about this here: Bad habits to kick: using SELECT * / omit the column list ).
Use this code as a sample/template:
string insertQuery = #"INSERT INTO dbo.Table1 (FirstName, LastName, City)
VALUES (#FirstName, #LastName, #City);";
using (SqlCommand cmd = new SqlCommmand(insertQuery, con))
{
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstname.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar, 50).Value = lastname.Text;
cmd.Parameters.Add("#City", SqlDbType.VarChar, 50).Value = city.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close()
}
You should specify the columns names. For example:
cmd.CommandText = $"Insert into Table1 ({ColumnName of firstname}, { ColumnName of lastname}, { ColumnName of city})
values({firstname.Text}, {lastname.Text}, {city.Text})";
You can better use a stored procedure - something like that:
cmd.CommandText = "your SP name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = firstName.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = lastName.Text;
etc...
I'm making a form on C# that inserts data in a table with a where clause, but it's not working. I think the syntax of my query is the problem but I can't solve it.
This is the one that I tried that's working, but I need an insert query with a where clause.
SqlCommand addEmp = new SqlCommand("INSERT INTO tbl_Expenses " +
"(InvestedMoney,EstimatedServingCount,MealName) " +
"VALUES (#inv, #est, #mname)", conn);
addEmp.Parameters.AddWithValue("#mname", textBox1.Text);
addEmp.Parameters.AddWithValue("#inv", textBox2.Text);
addEmp.Parameters.AddWithValue("#est", textBox3.Text);
conn.Open();
addEmp.ExecuteNonQuery();
conn.Close();
I tried this code below:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Meal" +
" ExpensesID, MealName, MealPrice, ImageName, Imageblob)" +
"SELECT ExpensesID, #mname, #mprice, #imname, #img " +
"FROM tbl_Expenses" +
"WHERE MealName = '"+textBox1.Text+"'",conn);
cmd.Parameters.AddWithValue("#mname", textBox1.Text);
cmd.Parameters.AddWithValue("#mprice", textBox4.Text);
cmd.Parameters.AddWithValue("#imname", textBox1.Text);
cmd.Parameters.Add("#img", SqlDbType.Image, photo.Length).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
But I get this error:
System.Data.SqlClient.SqlException: Incorrect syntax near '='
This section is missing a space between the lines:
"from tbl_Expenses" +
"WHERE MealName = '"
so the sql code references a table named tbl_ExpensesWHERE, gives the table an alias of MealName, and then has an out-of-place =.
But you should also already know from the use of parameters elsewhere it is NOT okay to substitute textBox1.Text into the query like that. NEVER do that. Not even once. Not even for practice/learning code!
There are some other poor practices in here, but that was the worst. Here's a better pattern:
string sql = #"
INSERT into tbl_Meal
(ExpensesID,MealName,MealPrice,ImageName,Imageblob)
SELECT
ExpensesID,#mname,#mprice,#mname,#img
FROM tbl_Expenses
WHERE MealName = #mname";
using (var conn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, conn))
{
//wild guess at column types. Use actual column types/size FROM THE DATABASE
cmd.Parameters.Add("#mname", SqlDbType.NVarChar, 30).Value = textBox1.Text;
cmd.Parameters.Add("#mprice", SQlDbType.Decimal, 18, 8).Value = textBox4.Text;
//use the size of the column here, not the length of the photo
cmd.Parameters.Add("#img", SqlDbType.Image, 8000).Value = photo;
conn.Open();
cmd.ExecuteNonQuery();
}
Instead of Parameters.AddWithValue() use Parameters.Add() and also use correct datatypes, for example EstimatedServingCount seems to be an int, but however AddWithValue can not know that:
addEmp.Parameters.Add("#mname", SqlDbType.VarChar).Value = textBox1.Text;
addEmp.Parameters.Add("#inv", SqlDbType.VarChar).Value = textBox2.Text;
addEmp.Parameters.Add("#est", SqlDbType.Int).Value = textBox3.Text;
This is basically a method to insert a record into a table. It was working fine before I decided to add in a way to check if the Customer ID already exists in the database. I get a
'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Procedure or function InsertCustomer has too many arguments specified.
on the line
command.ExecuteNonQuery();
I don't understand what's wrong.
public void add()
{
lblMessage.Text = "";
command.Connection = conn;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "CheckDetails";
command.Parameters.AddWithValue("#CustID", txtCID.Text);
conn.Open();
int check = (int)command.ExecuteScalar();
if (check == 0)
{
command.CommandText = "InsertCustomer";
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
command.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = txtFName.Text;
command.Parameters.Add("#Surname", SqlDbType.VarChar).Value = txtLName.Text;
command.Parameters.Add("#Gender", SqlDbType.VarChar).Value = rdoGender.Text;
command.Parameters.Add("#Age", SqlDbType.Int).Value = txtAge.Text;
command.Parameters.Add("#Address1", SqlDbType.VarChar).Value = txtAdd1.Text;
command.Parameters.Add("#Address2", SqlDbType.VarChar).Value = txtAdd2.Text;
command.Parameters.Add("#City", SqlDbType.VarChar).Value = txtCity.Text;
command.Parameters.Add("#Phone", SqlDbType.VarChar).Value = txtPhone.Text;
command.Parameters.Add("#Mobile", SqlDbType.VarChar).Value = txtMobile.Text;
command.Parameters.Add("#Email", SqlDbType.VarChar).Value = txtEmail.Text;
command.ExecuteNonQuery();
lblMessage.Text = "Customer Details Added.";
}
else
{
lblMessage.Text = "Customer ID already exists.";
}
conn.Close();
}
You are adding the same parameter twice:
command.Parameters.AddWithValue("#CustID", txtCID.Text);
// ....
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
You can use command.Parameters.Clear();. But i'd prefer to use two different SqlCommands for the two procedures CheckDetails and InsertCustomer to avoid such issues.
Side-note: don't let the database try-cast the value for you. Use int.TryParse.
Remove below parameter from your statement, you already add parameter in command:
command.Parameters.Add("#CustID", SqlDbType.Int).Value = txtCID.Text;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO myTbl ([username],[password],[firstname],[lastname],[mi],[age],[place],[contact])VALUES (?,?,?,?,?,?,?,?)";
command.Parameters.Add("#user", OleDbType.VarChar).Value = txtUsername.Text;
command.Parameters.Add("#psw", OleDbType.VarChar).Value = txtPassword.Text;
command.Parameters.Add("#nm", OleDbType.VarChar).Value = txtName.Text;
command.Parameters.Add("#Lname", OleDbType.VarChar).Value = txtLastName.Text;
command.Parameters.Add("#mIni", OleDbType.VarChar).Value = txtMI.Text;
command.Parameters.Add("#ag", OleDbType.Integer).Value = Convert.ToInt32(txtAge.Text);
command.Parameters.Add("#plc", OleDbType.VarChar).Value = txtPlace.Text;
command.Parameters.Add("#cntct", OleDbType.Integer).Value = Convert.ToInt32(txtContact.Text); ;
command.ExecuteNonQuery();
lblInfo.Visible = true;
lblInfo.Text = "Success";
conn.Close();
This gives me the error Input string was not in a correct format. Please help me out.
Based on the code, and the error, most likely one of the TextBox control's text (txtContact or txtAge) isn't a valid Integer (whole number) value. Ensure that you're validating the input. You should use a RequiredFieldValidator, and either a RangeValidator or RegularExpressionValidator to ensure that the Textbox is not empty and contains valid text.
You might also consider using System.Int32.TryParse() instead of Convert.ToInt32.
You are converting non integer value to integer value, please check txtAge.Text and txtContact.Text and their values, they should contain value which convert into integer value.