when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?
protected void btnAddBook_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (#Title, #Author, #Price, #Edition)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#Author", TextBox2.Text);
cmd.Parameters.AddWithValue("#Price", TextBox3.Text);
cmd.Parameters.AddWithValue("#Edition", TextBox4.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.
You could try to force the AddWithValue to create a numeric parameter with
cmd.Parameters.AddWithValue("#Price", Convert.ToDecimal(TextBox3.Text));
(Of course assuming a decimal Price column)
Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.
Related
I wanted to insert values into database but it is not working eventhough my code perfectly working when its used as stored procedure. I am trieng to use button click to store the value. Please tell whats wrong with the code. Its not showing any error or exception but data is not getting updated in the table
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES ('12', 'abcd', '20')";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
my columns acnum and shares_bought are "int" and scripname is
"varchar"
Then you will not need single quotes for your integer values. Use it as;
...VALUES (12, 'abcd', 20)"
A few things more;
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
You don't need cmd.CommandType = CommandType.Text line. It is .Text by default.
var conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
using(var sqlConnection1 = new SqlConnection(conStr))
using(var cmd = sqlConnection1.CreateCommand())
{
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES (12, 'abcd', 20)";
sqlConnection1.Open();
cmd.ExecuteNonQuery();
}
Set breakpoint in code and see if code is executing. In case you don't know how to, see here.
As you are not getting any exception on insert statement and it's not reflecting in database, either you have different connection string or your code is not getting executed.
My query seems to be correct but why is this happening?
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Sparrow vivek\Documents\Billing.accdb";
con.Open();
DateTime a = Convert.ToDateTime(label2.Text);
String query = "INSERT INTO balancesheet (BillNumber,CusName,Date,Amount) values (?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("?",label3.Text);
cmd.Parameters.AddWithValue("?", label4.Text);
cmd.Parameters.AddWithValue("?", a.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("?", label6.Text);
cmd.ExecuteNonQuery();
con.Close();
Your query contains a reserved keyword: Date. To use it you need to use square brackets around that name
String query = "INSERT INTO balancesheet (BillNumber,CusName,[Date],Amount) values (?,?,?,?)";
It is highly recommended to avoid these names. If it is still possible change that name ASAP.
Now let's examine that list of AddWithValue. In this method the datatype of the parameter is automatically determined by the value that you pass. You have every value passed to the parameter collection of type string. But it is probable that your database fields doesn't want a string as value. For example Date,Amount seems requires a datetime and a number
cmd.Parameters.AddWithValue("?",label3.Text);
cmd.Parameters.AddWithValue("?", label4.Text);
cmd.Parameters.AddWithValue("?", a);
cmd.Parameters.AddWithValue("?", Convert.ToDecimal(label6.Text));
I have tried the following code to save to a database. The condition is are, I have a value in a dropdown list and the values are New= 1, and old=2. If the user selects 1 or new then it will save data to database or if they select old then it will show the exist data.
Now this time my label shows data inserted but the data is not saved to the table (But doesn't show any error).
protected void btnsave_Click(object sender, EventArgs e)
{
if (ddl.Text=="1")
{
cs.Open();
string query = "insert into resig (#id,#name,#email) values('"+txtgn.Text+"','"+txtgname.Text+"','"+txtsg.Text+"')";
SqlCommand cmd = new SqlCommand(query,cs);
lbdmsg.Text = "Data Inserted";
//txtgname.Text = ddl.SelectedItem.ToString();
}
else
{
cs.Open();
string query = "select name, email from resig where id='" + txtgn + "'";
SqlCommand cmd= new SqlCommand(query,cs);
dr =cmd.ExecuteReader();
while(dr.Read())
{
string name= txtgname.Text;
string email=txtsg.Text;
}
cs.Close();
}
}
I see 2 things;
You are try to parameterize your column names, not your values.
You are not executing your insert command with ExecuteNonQuery().
You should use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
if (ddl.Text == "1")
{
string query = "insert into resig (id,name,email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query,cs);
cmd.Parameters.AddWithValue("#id", txtgn.Text);
cmd.Parameters.AddWithValue("#name", txtgname.Text);
cmd.Parameters.AddWithValue("#email", txtsg.Text);
cs.Open();
cmd.ExecuteNonQuery();
}
Call cmd.ExecuteNonQuery() to run the command on your db
Your SQL is both wrong, and very dangerous/susceptible to SQL injection. The first list in parenthesis must be a column list, and the values list should be parameters to avoid SQL injection:
string query = "insert into resig (id, name, email) values(#id, #name, #email)";
SqlCommand cmd = new SqlCommand(query, cs);
cmd.Parameters.Add(new SqlParameter("#id", txtgn.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtgname.Text));
cmd.Parameters.Add(new SqlParameter("#email", txtsg.Text));
cmd.ExecuteNonQuery();
You should parameterize the select statement as well. Why is this important? Consider the resulting SQL if the user entered this for id and selected old:
'; delete resig; --
Building SQL by concatenating user input opens your database to the whim of users with bad intentions, and in this day and age should never be used. Countless web sites have been defaced and had their data corrupted -- it was ill-considered back in the day, but now we know better, and there's no excuse.
I have a this Items table in ms access
Items(Table)
Item_Id(autonumber)
Item_Name(text)
Item_Price(currency)
and i'm trying to insert a record using this code.
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString());
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values ('" + itemNameTBox.Text + "','" + Convert.ToDouble(itemPriceTBox.Text) + "')";
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myCon.Close();
Code is running without error but at the end no record is found in the table what mistake i'm doing?
Your sql insert text doesn't use parameters.
This is the cause of bugs and worse (SqlInjection)
Change your code in this way;
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString()))
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values (?,?)";
cmd.Parameters.AddWithValue("#item", itemNameTBox.Text);
cmd.Parameters.AddWithValue("#price", Convert.ToDouble(itemPriceTBox.Text));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
Of course this assumes that the text box for price contains a correct numeric value.
To be sure add this line before calling the code above
double price;
if(double.TryParse(itemPriceTBox.Text, out price) == false)
{
MessageBox.Show("Invalid price");
return;
}
then use price as value for the parameter #price
**EDIT 4 YEARS LATER **
This answer needs an update. In the code above I use AddWithValue to add a parameter to the Parameters collection. It works but every reader should be advised that AddWithValue has some drawbacks. In particular if you fall for the easy path to add just strings when the destination column expects decimal values or dates. In this context if I had written just
cmd.Parameters.AddWithValue("#price", itemPriceTBox.Text);
the result could be a syntax error or some kind of weird conversion of the value and the same could happen with dates. AddWithValue creates a string Parameter and the database engine should convert the value to the expected column type. But differences in locale between the client and the server could create any kind of misinterpretation of the value.
I think that it is always better to use
cmd.Parameters.Add("#price", OleDbType.Decimal).Value =
Convert.ToDecimal(itemPriceTBox.Text);
More info on AddWithValue problems can be found here
I'm trying to switch come of my SQL queries to parameter queries but i keep getting some errors shown after the code below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (#Surname,[#Other Names],#mobileno,#date, #email, #faculty, #dept, [#Registration Number], #session,#thesis, #yearGrad, #tellerno, #amount, #address,#question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("#Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("#[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("#mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("#date", lblDate.Text);
cmd.Parameters.AddWithValue("#email", lblEmail.Text);
cmd.Parameters.AddWithValue("#faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("#dept", lblDept.Text);
cmd.Parameters.AddWithValue("#[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("#session", lblSession.Text);
cmd.Parameters.AddWithValue("#thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("#yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("#tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("#amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#address", lblAdd.Text);
cmd.Parameters.AddWithValue("#question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
Error message is:
Server Error in '/TranscriptReloaded' Application.
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#date".
"date" is a SQL reserved word, so the translation to SQL may be having a problem with it. Generally speaking you should avoid using the word date on its own as column names or as parameters.
Personally I would start by losing the #[two word] variable names (which you also use as [#two word] elsewhere). I don't know if this is the cause, but I have never seen this usage personally, and I'm dubious. Fine for column names (and table names), but variables? Not so sure. Changing the variable names is local to this code, so shouldn't cause any side-effects.