This question already has an answer here:
add user input in database [closed]
(1 answer)
Closed 9 years ago.
I am trying to implement this
Console.WriteLine("Enter Name: ");
this.name = Console.ReadLine();
string sql1 = "insert into items values ( " + this.name ")";
DataAccess.ExecuteSQL(sql1);
when I try to input data through this it showing error about , unhanded exception , column name or number not found.
I am sure column name is ok and I gave it varchar(50) type. Is this method not permitted?
Thank you in advance.
Well first of all you don't have quotes around your string. You're also missing a plus sign. It should be like:
string sql1 = "insert into items values ( '" + this.name + "')";
However, this is a really bad way of handling your SQL queries through C#. You should be using parameterized queries! There are a lot of bad things that can happen to your database if you do things like this...
See the example of using the SqlCommand class with parameters at the bottom of this page:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx
You need to provide quotes if the field is a varchar:
string sql1 = "insert into items values ( '" + this.name + "')";
Be careful of sql injection though, parameterized queries are better.
Related
I'm having problems with some code I'm trying to write. I'm doing something for suppliers orders, so I have a table which is named "encomendas_fornecedores" with a autoincrement field before the key that is the code of sale which consists in a EF before the number(which is a text field).
Here is the code:
connection.Open();
OleDbCommand comando1 = new OleDbCommand();
OleDbCommand comando2 = new OleDbCommand();
OleDbCommand comando3 = new OleDbCommand();
comando1.Connection = connection;
comando2.Connection = connection;
comando3.Connection = connection;
comando1.CommandText = "INSERT INTO encomendas_fornecedores (cod_encomenda_forn, cod_metodo, cod_forn, total_pagar_forn) VALUES('FO', '" + txtcodmetodo.Text + "', '" + txtcodforn.Text + "', '" + lbltotalapagar.Text + "'); ";// insert into table the values with a FO to cod
comando1.ExecuteNonQuery();
comando2.CommandText = "Select MAX(num_encomenda) From encomendas_fornecedores;";// selecting maximum num encomenda so I can isolate it and add to a text before(btw I do this in php/sql no problems
int numero = Convert.ToInt32(comando2.ExecuteScalar());//max num_encomenda
string codencomendaforn= "EF"+Convert.ToString(numero);// sales code completed
comando3.CommandText = "UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = '"+ numero +"';";//query that is giving me the problems, it says something like "type of data incorrect in data expression"
comando3.ExecuteScalar();//giving me error this line
connection.Close();
But now here's the catch the cod_encomenda_forn is text and the num_encomenda auto increment as it is in the sql, and I tried to show the query in a textbox to see if its anything is wrong but nothing seems wrong.
"UPDATE encomendas_fornecedores SET cod_encomenda_forn = '"+codencomendaforn+"' WHERE num_encomenda = **'**"+ **numero** +"**'**;";//query that is giving me the problems,it says something like "type of data incorrect in data expression"
You are passing a string numero to a where statement that seems like it is expecting a number. As long as it is numeric it should work, but definitely not gauranteed to work. Second you are passing anothercodencomendaforn string to encomenda what is encomenda 's data type?
It appears that you are not handling potential datatype differences between your c# code and your SQL query. In addition single quoting '' around a value in a SQL statement tells the database engines that it is a string even if that is '1234'. While SQL will automatically convert some values it doesn't always. In addition c# .net library also looks for some conversion etc. before sending the SQL statement. To fix appropriately use parameters that are data typed to the database type in the SQL table. To fix it simply in the statement figure out your data types and fix the '' single quotes appropriately.
PS the people trying to help you in the comments were being nice and telling you the professional way of keeping your job in the future when you graduate after fixing this issue.
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
my_con.Open();
OleDbCommand o_cmd1 = my_con.CreateCommand();
o_cmd1.CommandText = "INSERT INTO Personal_Details(Date,Time,Patient_Name,Contact_Number,Gender,Allergic_To,KCO) VALUES ('" + DateTime.Now.ToString("dd-MM-yyyy") + "','" + DateTime.Now.ToString("h:mm:ss tt") + "','" + txtPatientName.Text + "','" + txtContactNo.Text + "','" + comboBoxGender.Text + "','" + txtAllergic.Text + "','" + txtKCO.Text + "')";
int j = o_cmd1.ExecuteNonQuery();
I am getting the Syntax error in Insert Statement I don't understand what is mistake if any one help me I am really thank full.Thanks in Advance.
Date and Time are typically reserved keywords in many database systems. You should at the very least wrap them with [ ]. More preferably, if you are designing the table, change the field name to something more descriptive. For example if the Date and Time represented a reminder then you could use ReminderDate and ReminderTime so as not to interfere with reserved keywords.
And follow the parameter advice that's already been given.
Use command parameters instead of concatenating strings. Your code is open for SQL Injection attacks or in your specific case the problem may be related with invalid user input. Try to thing about this situation:
What if the txtContactNo.Text returns this string "Peter's contact is +123456" ? How does the SQL query will look then? Pay close attention to ' character.
You should ALWAYS use parametrized SQL queries no matter how good you thing your input validation is. It also has more advantages like query plan caching etc.
So in your case the code must be written like this:
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
using(my_con)
{
my_con.Open();
using(OleDbCommand o_cmd1 = my_con.CreateCommand())
{
o_cmd1.CommandText = #"
INSERT INTO Personal_Details ([Date], [Time], Patient_Name, Contact_Number, Gender, Allergic_To, KCO)
VALUES (#date, #time, #name, #contNo, #gender, #alergic, #kco)";
o_cmd1.Parameters.AddWithValue("#date", DateTime.Now.ToString("dd-MM-yyyy"));
o_cmd1.Parameters.AddWithValue("#time", DateTime.Now.ToString("h:mm:ss tt"));
o_cmd1.Parameters.AddWithValue("#name", txtPatientName.Text);
o_cmd1.Parameters.AddWithValue("#contNo", txtContactNo.Text);
o_cmd1.Parameters.AddWithValue("#gender", comboBoxGender.Text);
o_cmd1.Parameters.AddWithValue("#alergic", txtAllergic.Text);
o_cmd1.Parameters.AddWithValue("#kco", txtKCO.Text);
o_cmd1.ExecuteNonQuery();
}
}
Also make sure that you are properly disposing the connection and the command objects (by using :) the using keyword)
For more info read the docs in MSDN
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx
string sql = "insert into tblmain values('" + txtName.Text + "','" + txtPost.Text + "','" + DropDownList1.SelectedItem + "')";
If the user inserts My name's first later is D ! in txtPost, then it gives error that 's are not allowed.
Can you please send me the code to accept this type of character from textbox in .net (C#).
You sample is the book example of SQL injection in most pure form. ' closes the previous quote and the rest of SQL command is interpreted differently from what you expect.
There is no excuses to not using parametrized queries when dealing with non-hardcoded values and SqlConnection directly.
Also check these articles for mre details. Approximate sample (need more fields and not showing exception handling):
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand("insert into tblmain values(#name")", connection);
command.Parameters.Add("#name", SqlDbType.String);
command.Parameters["#name"].Value = customerID;
connection.Open();
Int32 rowsAffected = command.ExecuteNonQuery();
Console.WriteLine("RowsAffected: {0}", rowsAffected);
}
The second problem you may hit is if you pick wrong field type for the text - to be able to store characters you want you need Unicode string. Check out C#: DbType.String versus DbType.AnsiString post for details.
I've got a error which I can't understand. When I'm debugging and trying to run a insert statement, its throwing the following exception:
"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."
I have looked all over my code, and I can't find the mistake I've made.
This is the query and the surrounding code:
SqlConnection myCon = DBcon.getInstance().conn();
int id = gm.GetID("SELECT ListID from Indkøbsliste");
id++;
Console.WriteLine("LNr: " + listnr);
string streg = GetStregkode(navne);
Console.WriteLine("stregk :" + strege);
string navn = GetVareNavn(strege);
Console.WriteLine("navn :" + navne);
myCon.Open();
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(" + id + "," + listnr + ", '" + strege + "','" + navn + "'," + il.Antal + ", "+il.Pris+")";
Console.WriteLine(il.Antal+" Antal");
Console.WriteLine(il.Pris+" Pris");
Console.WriteLine(id + " ID");
SqlCommand com = new SqlCommand(query, myCon);
com.ExecuteNonQuery();
com.Dispose();
myCon.Close();
First of all check the connection string and confirm the database location and number of columns a table has.
Suggestion : Do not use hardcoded SQL string. Use parameterized sql statements or stored-proc.
Try parameterized way,
string query = "INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris)
Values (#ListID, #ListeNr, #Stregkode, #Navn, #Antal, #Pris)"
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.Add("#ListID",System.Data.SqlDbType.Int).Value=id;
com.Parameters.Add("#ListeNr",System.Data.SqlDbType.Int).Value=listnr;
com.Parameters.Add("#Stregkode",System.Data.SqlDbType.VarChar).Value=strege ;
com.Parameters.Add("#Navn",System.Data.SqlDbType.VarChar).Value=navn ;
com.Parameters.Add("#Antal",System.Data.SqlDbType.Int).Value=il.Antal;
com.Parameters.Add("#Pris",System.Data.SqlDbType.Int).Value=il.Pris;
com.ExecuteNonQuery();
Please always use parametrized queries. This helps with errors like the one you have, and far more important protects against SQL injection (google the term, or check this blog entry - as an example).
For example, what are the actual values of strege and/or navn. Depending on that it may render your SQL statement syntactically invalid or do something worse.
It (looks like) a little more work in the beginning, but will pay off big time in the end.
Are you using danish culture settings?
In that case if il.Pris is a double or decimal it will be printed using comma, which means that your sql will have an extra comma.
Ie:
INSERT INTO Indkøbsliste (ListID, ListeNr, Stregkode, Navn, Antal, Pris) Values(33,5566, 'stegkode','somename',4, 99,44)
where 99,44 is the price.
The solution is to use parameters instead of using the values directly in you sql. See some of the other answers already explaining this.
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string x = Request.QueryString["SubId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
{
comCmd.ExecuteNonQuery();
}
}
}
An INSERT can't have a WHERE clause. It makes no sense to have one, you're putting data in, not narrowing it down.
If you're trying to change preexisting data, that's an UPDATE, not an INSERT. Here's an example:
"UPDATE Submission
SET Status='decline', StatusComment='" + TbComments.Text + "', StatusValue = 2
WHERE SubmissionId = " + x
That is incorrect INSERT syntax. Correct INSERT syntax is:
INSERT INTO tableName (columnList) VALUES (valueList)
columnList and valueList must have same count of items and values must be of type expected by columns.
or
INSERT INTO tableName (columnList)
SELECT columnList2
FROM tableName2
WHERE conditionsFromTable2
columnList and columnList2 must have same count of items of same types. You can use any complicated select joined over multiple tables with condition applied on data from these tables.
You need to use UPDATE, not INSERT
INSERT insert new row, therefore WHERE makes no sense
Where clause is not allowed in Insert query. Form your code I guess that you need to use Update query.
You'r trying to INSERT INTO Submission data from TbComments. So you need to SELECT the data from TbComments and then INSERT INTO Submission
string comQuery =
"INSERT INTO Submission (
Status,
StatusComment,
StatusValue)
SELECT
'decline',
TbComments.Text,
2)
FROM TbComments
WHERE SubmissionId =" + x;
So your SQL statement is:
"INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES (blah) WHERE SubmissionId =" + x;
The problem is definitely the WHERE. WHERE isn't valid for INSERT - See the MSDN documentation for the Insert command. Since you're filtering by SubmissionId, you probably want to do an UPDATE instead.
As for a better way of finding the problem, learning to use the MSDN documentation is a good step. A quick Google search for "msdn t-sql insert" will give you the page I linked to earlier in this answer. Documentation, experience, Google and Stack Overflow. That's how you find solutions :)