I Have a website which creates new order and saves shopping bag items into database.
The thing is that insert into,select,update,delete sentences are working in all my tables except one, i think i wrote the sentence perfectly but its still throw excption that says something wrong with the sentence.
string OrderSql = string.Format(#"
INSERT INTO Order ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend])
VALUES ({0},{1},{2},{3},'{4}')",
UserId, DateTime.Now, Price, 1, Address);
at first i thought the problem may be found at the db so i copied my db into new once still doesnt working
i would send the relationship between tables but i need 10 rep..
It looks like you have two issues. Firstly as #juergen points out in the comments order is a reserved word so you'll need to enclose it in square brackets. Secondly, you don't have the date enclosed in quotes. So your code should read:
string OrderSql = string.Format(#"INSERT INTO [Order] ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend])
VALUES ({0},'{1}',{2},{3},'{4}')", UserId, DateTime.Now, Price, 1, Address);
Note the square brackets around Order and the single quotes around {1}.
However, you are open to SQL Injection attacks using that code so I would strongly suggest you read up on using parameterized queries. #DJ KRAZE has added a link in the comments to this question which should point you in the right direction.
you can also create a method call it and do something like this.
This would require that you create a stored procedure with the #Parameters shown in this example ** if this is Access then petelids Answer will be a great starting point if this is SQL Server then what I have posted would work for you
private void InsertMyData(string UserId, DateTime DayMonthYear, double Price, string Address)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO [Order] ([UserID],[DayMonthYear],[PriceToPay],[StatusID],[AdressToSend])
VALUES (#UserId, #DayMonthYear, #Price, 1, #Address)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#UserId", UserId);
cmd.Parameters.AddWithValue("#DayMonthYear", DayMonthYear);
cmd.Parameters.AddWithValue("#PriceToPay", Price);
cmd.Parameters.AddWithValue("#StatusID", 1);
cmd.Parameters.AddWithValue("#AdressToSend", Adress);
connection.Open();
cmd.ExecuteNonQuery();
}
}
Related
In SQL Server
update incident_info
set description = N'ဆေးလိပ်'
where incidentid = 5
This query is correct in SQL Server and shows myanmar font correctly in the database.
I want to write correct query as above in below insert query.
sqlUtil.SqlDataUpdate(false, ("INSERT INTO Incident_Info (incidentid, incidentdate, incidenttime, description, Salesmen_id, name, phone, email, address, cost, currency, solution, status)" +
"VALUES (#incidentid, #incidentdate, #incidenttime, N'+#description+', #salesmenid, N'+#name+', #phone, #email, N'+#address+', #cost, #currency, N'+#solution+', #status)"), SysController.dicParams);
You do NOT need to prefix your SQL parameter names with a N prefix - that's useless, and probably results in an error. The N prefix is only needed when specifying a Unicode string literal in a raw SQL code snippet.
In your case, what you need to ensure is that the code that does the actual insert into SQL Server properly defines your parameters as SqlDbType.NVarChar. So in your sqlUtil class, somewhere, you have a method SqlDataUpdate that parses and executes that SQL statement you send in.
Inside there, you must ensure that code something like this is used:
using (SqlConnection conn = new SqlConnection(-your-connection-string-here-))
using (SqlCommand insertCmd = new SqlCommand(sqlQuery, conn))
{
// here, you need to ensure you define your string parameters correctly
insertCmd.Parameters.Add("#description", SqlDbType.NVarChar, 100);
.....
// and then you need to set the values - since .NET strings are inherently Unicode, no special treatment is needed
insertCmd.Parameters["#description"].Value = SysController.dicParams.......
.....
// open, execute, close
conn.Open();
int rowsInserted = insertCmd.ExecuteNonQuery();
conn.Close();
}
This must be done inside your sqlUtil class - you cannot influence this from the "outside" by simply adding a N prefix to your parameter names...
How do I make it so that my query only update the data I want?
Here's the current code
string query = string.Format("update Customer set title='{0}',[Name]='{1}'",titleComboBox2.Text,nameTextBox2.Text,"where ID="+idTextBox+"");
Apparently the last part of the query isn't working. Why it is that?
Because you didn't use any index argument as {2} for your third argument which is WHERE part.
That's why your query will be contain only update Customer set title='{0}',[Name]='{1}' part this will be update for your all rows since it doesn't have any filter.
Fun fact, you could see this as query if you would debug your code.
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Let's assume you use ADO.NET;
using(var con = new SqlConnection(conString))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"update Customer set title = #title, [Name] = #name
where ID = #id";
cmd.Paramter.Add("#title", SqlDbType.NVarChar).Value = titleComboBox2.Text;
cmd.Paramter.Add("#name", SqlDbType.NVarChar).Value = nameTextBox2.Text;
cmd.Paramter.Add("#id", SqlDbType.Int).Value = int.Parse(idTextBox.Text);
// I assumed your column types.
con.Open();
cmd.ExecuteNonQuery();
}
Currently your query does not use WHERE clause, because it is ignored by string.Format. You have 3 placeholder parameters, and you are using only {0} and {1}, so WHERE part is never added to the SQL query. Change your query to include WHERE clause, e.g. like this:
string query = string.Format("update Customer set title='{0}',[Name]='{1}' {2}",titleComboBox2.Text,nameTextBox2.Text,"where ID="+idTextBox.Text+"");
However, there is one very serious flaw in your code - it is vulnerable to SQL injection attack. There are hundreds of articles about it online, make sure to read about what that is and how to update your code accordingly (hint - parametrize queries)
I have the statement in c# :
String sql = String.Format("UPDATE Table SET FIRST_NAME='{0}',LAST_NAME='{1}',BIRTH_DATE='{2}' where CUSTOMER_NUMBER ='{3}'",FirstName, LastName,DateOfBirth,Number);
The above statement doesn't execute if the first name,last name etc have apostrophe like O'Hare,O'Callahagan because of this the update statement gets the wrong syntax.
How to escape the apostrophe in string.format?
How to escape the apostrophe in string.format?
Don't escape it, use parameterized query instead.
Imagine a user with a really unconventional name strongly resembling SQL statements for dropping a table or doing something equally malicious. Escaping quotes is not going to be of much help.
Use this query instead:
String sql = #"UPDATE Table
SET FIRST_NAME=#FirstName
, LAST_NAME=#LastName
, BIRTH_DATE=#BirthDate
WHERE CUSTOMER_NUMBER =#CustomerNumber";
After that, set values of FirstName, LastName, DateOfBirth, and Number on the corresponding parameters:
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.AddWithValue("#FirstName", FirstName);
command.Parameters.AddWithValue("#LastName", LastName);
command.Parameters.AddWithValue("#BirthDate", BirthDate);
command.Parameters.AddWithValue("#CustomerNumber", CustomerNumber);
Your RDMBS driver will do everything else for you, protecting you from malicious exploits. As an added benefit, it would let you avoid issues when the date format of your RDBMS is different from your computer: since your date would no longer be passed as a string representation, there would be no issues understanding which part of the formatted date represents a day, and which one represents a month.
You should use parameterized queries:
using (SqlCommand cmd = new SqlCommand("UPDATE Table SET FIRST_NAME= #FirstName, LAST_NAME= #LastName, BIRTH_DATE=#BirthDate where CUSTOMER_NUMBER = #CustomerNumber"))
{
cmd.Parameters.Add(new SqlParameter("FirstName", FirstName));
cmd.Parameters.Add(new SqlParameter("LastName", LastName));
cmd.Parameters.Add(new SqlParameter("BirthDate", DateOfBirth));
cmd.Parameters.Add(new SqlParameter("CustomerNumber", Number));
// Now, update your database
} // the SqlCommand gets disposed, because you use the 'using' statement
By using parameterized queries, you solve your problem. Using parameterized queries has two other advantages:
Protection against SQL Injection
Readability
Use parameterized query.
string commandString = "insert into MyTable values (#val1, #val2)";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("val1", "O'Hare");
command.Parameters.AddWithValue("val2", "O'Callahagan");
command.ExecuteNonQuery();
I'm using Visual C# connected to MySQL for study purposes and I'm stuck in throwing an error to the user when he types a username that already exists.
Current code to put things into the database (it may be useless, once my question may be much more about SQL):
s = new sql(); // This calls a class that works as an adapter to connect form with the database
Conn = s.Connection;
Conn.Open();
coma = Conn.CreateCommand();
coma.CommandText = "INSERT INTO test.test (`user`,`password`) VALUES ('"+username.Text+"','"+password.Text+"');";
coma.ExecuteNonQuery();
What I want to do it compare "username.Text" ("username" is a TextBox) with the values on database's "test" table and, if some value match, evoke a MessageBox.Show("Hey guy, this username is already in use! Try something different)
Some points about your code sample
You want to be sure that you dispose of your connection and command objects. For my answer, I've wrapped them in using statements which will take care of that for me.
You do not want to go to the database with unsanitized inputs. I am going to use parameterized queries in the example.
It's not a good idea to store passwords in plain text. I am not going to demonstrate more secure techniques, just know to look for information about encrypting passwords, salt keys, etc.
And now for some code. In this, I'm using OleDb objects, retrofit to your particular database. And, of course, provide appropriate names to tables, columns, etc.
using (OleDbConnection connection = SomeMethodReturningConnection())
using (OleDbCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OleDbParameter("#username", username));
command.CommandText = "Select Count(*) From Users where Username = #username";
connection.Open();
int output = (int)command.ExecuteScalar();
if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: #username parameter already exists, do not need to add again
command.Parameters.Add(new OleDbParameter("#password", password));
command.CommandText = "Insert Into Users (Username, Password) Values (#username, #password)";
command.ExecuteNonQuery();
}
}
Thank you Anthony! Your answer put me on the right track. Although there is something that the people who will read this post should change from your code in order to get it working with Odbc connectors: the way as parameters are parsed and the way as the textbox content is extracted:
using (OdbcConnection connection = SomeMethodReturningConnection())
using (OdbcCommand command = SomeMethodReturningCommand())
{
command.Parameters.Add(new OdbcParameter("#username", username.Text));
command.CommandText = "Select Count(*) From Users where Username = ?";
connection.Open();
int output = (int)command.ExecuteScalar();
if (output > 0)
{
// username already exists, provide appropriate action
}
else
{
// perform insert
// note: #username parameter already exists, do not need to add again
command.Parameters.Add(new OdbcParameter("#password", password.Text));
command.CommandText = "Insert Into Users (Username, Password) Values (?,?)**";
command.ExecuteNonQuery();
}
}
Thank you anyway!
I am trying to insert a integer into a database in C# using the code below, but everytime I run the compiler informs me that my integer is not a valid column "Invalid Column Name UserID"
Does anyone have any insight on this? Thanks.
Console.WriteLine("Please enter a new User Id");
string line = Console.ReadLine();
int UserID;
if (int.TryParse(line, out UserID))
{
Console.WriteLine(UserID);
Console.ReadLine();
}
//Prepare the command string
string insertString = #"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES (UserID,'Ted','Turner')";
First things first, I would get into the habit of using parameterised queries, if you are not planning to use stored procedures. In your example, I would:
using (var command = new SqlCommand("INSERT INTO tb_User(ID, f_Name, l_Name) VALUES (#id, #forename, #surname)", conn))
{
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("forename", forename);
command.Parameters.AddWithValue("surname", surname);
command.ExecuteNonQuery();
}
Where id, forename, surname are the appropriate variables. Notice I am also using using blocks, this ensures that my objects are cleaned up after it has completed.
it is because the 'UserID' within your insertString : ..."VALUES (UserID"... is invalid.
you need to pass a value for the UserID such as: ..."VALUES ('myUserIDGoesHere'"...
Your string is not dynamically reading the variables. Use something like this:
string insertString =
string.Format(#"INSERT INTO
tb_User(ID,f_Name, l_Name) VALUES
({0},'{1}','{2}')", UserId, "Ted",
"Turner");
There are better ways depending on what kind of data access you're using, but this is just to make the point of how to correct the string.
The problem is the first argument in VALUES - it simply isn't defined. If this is meant to be the value the user has entered, then you need to add a parameter to the command and use that parameter in the SQL; for example:
cmd.Parameters.AddWithValue("#id", UserID);
An then use
VALUES(#id, ...
in the TSQL.
Also, generally you might want to have the system generate the unique id. A the simplest level this could have an IDENTITY defined (an automatic sequence).
Use a parameterized query:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var insertCommand = new SqlCommand(
#"INSERT INTO tb_User (ID, f_Name, l_Name)
VALUES (#ID, 'Ted', 'Turner')", connection))
{
insertCommand.Parameters.AddWithValue("#ID", userID);
insertCommand.ExecuteNonQuery();
}
}
To answer your question regardless of your approach, try:
string insertString = #"INSERT INTO tb_User(ID,f_Name, l_Name) VALUES ("
+ UserID + ",'Ted','Turner')";