Unable to insert a row with parameter - c#

I am trying following code:
try
{
SqlConnection conn = new SqlConnection("server=ARSLAN-LAPI\\SQLEXPRESS;" +
"Trusted_Connection=yes;" +
"database=OTTS; " +
"connection timeout=30");
conn.Open();
String name=UserName.Text;
String pwd=Password.Text;
String query = "INSERT INTO dbo.user (username,password)
VALUES(#username,#password)";
SqlCommand command = new SqlCommand(query, conn);
command.Parameters.Add("#username",name);
command.Parameters.Add("#password",pwd);
command.ExecuteNonQuery();
conn.Close();
ErrorMessage.Text="Well done!";
}
catch(SqlException ex)
{
ErrorMessage.Text="You failed!" + ex.Message;
}
Received error that
You failed!Incorrect syntax near the keyword 'user'.
Please guide me..

User is a reserved keyword, I strongly suggest to change that field name to something different.
However, if you still insist in using it, remember to enclose it in square brackets every time you need it.
string query = "INSERT INTO [dbo].[user] (username,password) VALUES(#username,#password)";

Try this:
INSERT INTO dbo.[user] (username,password) VALUES(#username,#password)

try something like this,
SqlCommand command = new SqlCommand(query, conn);
command.Parameters.Add("#username",SqlDbType.VarChar,50).Value = name;
command.Parameters.Add("#password",SqlDbType.VarChar,50).Value= pwd;
command.ExecuteNonQuery();

Related

Invalid object name 'Main' error when inserting into Database - C# (WebForms), MySql

I know plenty of people have these issues, and I've actually tried to implement some of the suggestions to my code, however I'm getting errors that just don't make sense to me. This is my first time implementing database calls to my code. Can someone please tell me what I'm doing wrong? The following error pops up: ERROR: Invalid object name 'Main'. This is actually triggered by my exception so at least something is working. Otherwise, I don't know what the issue is. On the DB end, I have (username VARCHAR, email VARCHAR and number NCHAR) Please see the code below
static string path = Path.GetFullPath(Environment.CurrentDirectory);
static string databaseName = "u_DB.mdf";
string connectionString = #"Data Source=(localdb)\MSSQLLocalDB;AttachDbFilename=" + path + #"\" + databaseName + "; Integrated Security=True;";
private void button1_Click(object sender, EventArgs e)
{
// string query = "INSERT INTO UserInfo '" + textBox1.Text + "' and password = '" + textBox2.Text + "'";
string query = "insert into Main ([username], [email], [number]) values(#username,#email,#number)";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = textBox3.Text;
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = textBox2.Text;
cmd.Parameters.AddWithValue("#number", SqlDbType.VarChar).Value = textBox1.Text;
int rowsAdded = cmd.ExecuteNonQuery();
if (rowsAdded > 0)
MessageBox.Show("Added to Database");
else
MessageBox.Show("Nothing was added");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
con.Close();
}
}
Firstly, as Chetan assumed, do you have a main table?
The syntax of the query you are using is :
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Furthermore,
AddWithValue(string parameterName, object value (<== The actual value to insert!));
in your case
AddWithValue("#number", textBox1.Text);
is enough.

Weird error in "insert into" command?

I know this may sound rubbish but that's the truth.
everytime when i try to run this code i get syntax error.
any idea why?
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Rock.accdb";
con.Open();
String query = "insert into category ([name],desc) values (#1,#2)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#1", textBox1.Text);
cmd.Parameters.AddWithValue("#2", textBox2.Text);
cmd.ExecuteNonQuery();
textBox1.Text = null;
textBox2.Text = null;
label4.Text = "New Category Created";
label4.ForeColor = Color.Green;
the error is: Syntax error in INSERT INTO statement # cmd.ExecuteNonQuery();
desc is also a keyword (for descending) and so you'd need:
String query = "insert into category ([name],[desc]) values (#1,#2)";
Change your insert query like this,
String query = "insert into category ([name], [desc]) values (#1,#2)";
desc is reserved word by default. Also, please close your connection by con.Close(); after executing the command.

Adding rows to a SQL Server database from data entered by user in asp.net c#

string ConnectionString = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Data (Name, Sur-Name, Score,Avg) VALUES ('" + fName + "','" + sName + "','" + lblScore.Text + "','" + lblAvg.Text + "');");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#Sur-Name", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
finally
{
connection.Close();
}
The error I keep getting is a runtime saying
Incorrect syntax near '-'. Incorrect syntax near '-'.
I used the try catch just so page would load and my scores show but the label says this Incorrect syntax as well, I was wondering could anyone please help me with what I am doing wrong
Thanks.
I think Sur-Name breaks your query. Use it with square brackets like [Sur-Name]
But more important, please use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. I see you tried to use but you never declare your parameter names in your query.
Also DATA might be a reserved keyword on future versions of SQL Server. You might need to use with also like [DATA]
Consider to use using statement to dispose your SqlConnection and SqlCommand.
using(SqlConnection connection = new SqlConnection(ConnectionString))
using(SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = #"INSERT INTO [Data] (Name, [Sur-Name], Score, Avg)
VALUES (#Name, #SurName, #Score, #Avg)";
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
try
{
connection.Open();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblData.Text = exc.Message;
}
}
You are trying to mix concatenated queries with parametrized. Always use parametrized queries, It will save you from SQL Injection.
SqlCommand cmd = new SqlCommand(#"INSERT INTO [Data] (Name, [Sur-Name], Score,Avg) VALUES (
#Name, #SurName, #Score, #Avg)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#Name", fName);
cmd.Parameters.AddWithValue("#SurName", sName);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.Parameters.AddWithValue("#Avg", lblAvg.Text);
Also consider enclosing your connection and command object in using statement.
As #Soner has mentioned in his answer, use Square brackets for Data and Sur-Name

it gives me an incorect syntax error 'vehiclereg'

string Update = "UPDATE VehicleReport" +
"SET VehicleReg ='"+textBox1.Text+"',CurrentOdometer ='"+textBox5.Text+"',NextService ='"+textBox6.Text+"'" +
"WHERE Vehiclenum ='"+comboBox1.Text+"' ;";
try
{
SqlConnection conn = new SqlConnection("Data Source=(local);Initial Catalog=FleetTrackingDatabase;Integrated Security=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand(Update, conn);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Updated");
conn.Close();
}
catch (System.Exception f)
{
MessageBox.Show(f.Message, "ERROR");
}
At least this is not correct:
string Update = "UPDATE VehicleReport" + "SET ...
you need to add a space between VehicleReport and Set
string Update = "UPDATE VehicleReport " + "SET....
Add spaces
"UPDATE VehicleReport" +
" SET VehicleReg ='"+textBox1.Text+"',CurrentOdometer ='"+textBox5.Text+"',NextService='"+textBox6.Text+"'" +
" WHERE Vehiclenum ='"+comboBox1.Text+"' ;";
There is missing space after table name :
string Update = "UPDATE VehicleReport"
string Update = "UPDATE VehicleReport "
and the same before WHERE
Can you try this,
string Update = "UPDATE VehicleReport SET VehicleReg ='"+textBox1.Text+"',CurrentOdometer ='"+textBox5.Text+"',NextService ='"+textBox6.Text+"'" + " WHERE Vehiclenum ='"+comboBox1.Text+"' ;";
I'm really shocked there are 4 answers but nobody mentioned about parameterized sql and SQL Injection attacks but anyway..
As others mentioned, you need spaces before your SET and WHERE words.
But more more more important is, DON'T USE THIS WAY. When you use string concatenations in your queries, your code will be open for SQL Injection. Instead of this, you should always use parameterizezd queries.
For example;
string Update = "UPDATE VehicleReport SET VehicleReg = #vehiclereg, CurrentOdometer = #current, NextService = #next WHERE Vehiclenum = #vehiclenum;";
SqlCommand cmd = new SqlCommand(Update, conn);
cmd.Parameters.AddWithValue("#vehiclereg", textBox1.Text);
cmd.Parameters.AddWithValue("#current", textBox5.Text);
cmd.Parameters.AddWithValue("#next", textBox6.Text);
cmd.Parameters.AddWithValue("#vehiclenum", comboBox1.Text);

Incorrect syntax inserting data into table

I am having some trouble with my update() method. The idea is that the user Provides a recipe name, ingredients, instructions and then selects an image using Filestream.
Once the user clicks 'Add Recipe' this will call the update method, however as things stand I am getting an error which is mentioning the contents of the text box:
Here is the update() method code:
private void updatedata()
{
// filesteam object to read the image
// full length of image to a byte array
try
{
// try to see if the image has a valid path
if (imagename != "")
{
FileStream fs;
fs = new FileStream(#imagename, FileMode.Open, FileAccess.Read);
// a byte array to read the image
byte[] picbyte = new byte[fs.Length];
fs.Read(picbyte, 0, System.Convert.ToInt32(fs.Length));
fs.Close();
//open the database using odp.net and insert the lines
string connstr = #"Server=mypcname\SQLEXPRESS;Database=RecipeOrganiser;Trusted_Connection=True";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string query;
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (" + textBox1.Text + "," + " #pic" + "," + textBox2.Text + "," + textBox3.Text + ")";
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "pic";
picparameter.Value = picbyte;
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.Add(picparameter);
cmd.ExecuteNonQuery();
MessageBox.Show("Image successfully saved");
cmd.Dispose();
conn.Close();
conn.Dispose();
Connection();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Can anyone see where I have gone wrong with the insert into Recipes query or suggest an alternative approach to this part of the code?
Your code is open to SQL Injection, but probably your error comes from some text that contains a single quote (the instructions fields for example) and this break your command string build using concatenating the user input.
EDIT
As someone pointed in comment the error is caused by the missing quotes around your textboxes. But while easy to fix that's not the way to go because it is wrong to fix the error adding the missing quotes. It is just postponig the problem leaving a big security hole waiting to be exploited.
A parameterized query could avoid all this mess.
string connstr = "....";
string query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) " +
"values (#name, #pic, #ing, #instr)";
using(SqlConnection conn = new SqlConnection(connstr))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
SqlParameter picparameter = new SqlParameter();
picparameter.SqlDbType = SqlDbType.Image;
picparameter.ParameterName = "#pic";
picparameter.Value = picbyte;
cmd.Parameters.Add(picparameter);
cmd.Parameters.AddWithValue("#name", textbox1.Text);
cmd.Parameters.AddWithValue("#ing", textbox2.Text);
cmd.Parameters.AddWithValue("#instr", textbox3.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Image successfully saved");
}
Since you using string concatenations, you probably missed a quote or you put an extra quote or missed a comma or put extra comma etc etc....
Don't use this way!
Your error doesn't look obviously but you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values (#p1, #pic, #p3, #p4)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue(#p1, textBox1.Text);
cmd.Parameters.AddWithValue(#pic, textBox1.Text);
cmd.Parameters.AddWithValue(#p3, textBox1.Text);
cmd.Parameters.AddWithValue(#p4, picparameter);
try this
query = "insert into Recipes(RecipeName,RecipeImage,RecipeIngredients,RecipeInstructions) values ('" + textBox1.Text + "'," + " #pic" + ",'" + textBox2.Text + "','" + textBox3.Text + "')";

Categories