I'm getting a strange syntax error when I run this in VB:
SQLString = "UPDATE Login SET Password = '" + PasswordTextBox.Text + "'"
SQLString += " WHERE UserName = '" + UserNameTextBox.Text + "'"
The Username is checked before getting to this part and is definitly in the database.
It gives an exception saying that there's a syntax error in update statement. Anyone have any idea what's wrong?
LOGIN is a reserved word in SQL Server (used for login account management), so in order to use it in a query (i.e. a column name) you need to escape it with [], so use [LOGIN] as the field name.
You should never use string concatenation and pass that to your SQL database, as you are exposing yourself to SQL Injection attacks.
You should use the SqlCommand object and pass through parameters. See this article on how to do so.
SQLString = "UPDATE [Login] SET Password = #password "
SQLString += " WHERE UserName = #userName"
...
dbCommand.Parameters.Add("#password", SqlDbType.VarChar, 50)
dbCommand.Parameters["#password"].Value = PasswordTextBox.Text
dbCommand.Parameters.Add("#userName", SqlDbType.VarChar, 50)
dbCommand.Parameters["#userName"].Value = UserNameTextBox.Text
I am pretty sure that Login is a reserved word, try changing Login to [Login]
Password is a reserved word so [Password] fixes it, my lecturer fixed to for me :)
Instead of showing how you're building the statement, show us what's in SQLString when the statement is executed.
Also, try enclosing the column and table names in the identifier quote characters, which are [ and ] for Microsoft, and ` (on the tilde key) for many others databases.
Without knowing what you are using for your actual password and username, my guess is that some character in one (or both) of those are causing the sql statement to end prematurely. You should really use parameters when executing sql like this.
Take a look at this: http://msdn.microsoft.com/en-us/library/ms998271.aspx
I agree with some of the previous answers, about using parameters (I gave + 1 to #Oded) and using [ ] with tablenames and fieldnames (I gave +1 to SQLMenace).
In conclussion, I think this is the most correct way to launch your query:
using(SqlConnection connection = new SqlConnection("<your connection string>"))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "UPDATE [Login] SET [Password] = #PasswordParameter WHERE [UserName] = #UserNameParameter";
command.Parameters.AddWithValue("#PasswordParameter", PasswordTextBox.Text);
command.Parameters.AddWithValue("#UserNameParameter", UserNameTextBox.Text);
command.ExecuteNonQuery();
}
I would recommend surrounding the words "login" and "password" with tick marks to let the handler know that they are not to be rendered as reserved words.
So:
Update 'login' SET 'password'
But rather than single-quotes, use the tick mark (upper-left key on the keyboard). I can't demonstrate it correctly as StackOverflow will treat it as a class if it's surrounded in tick marks.
Related
I try to execute a simple sql task with variable, so I create my variable and into it I insert delete statement like:
DELETE FROM fiscal_cxp WHERE EMPRESA = '"+#[User::cia]+"'
but when I try to evaluate expression I get an issue:
I review query several times but I dont find nothing wrong. Can someone knows what is wrong there? Regards
You're missing the opening and closing quotes:
"DELETE FROM fiscal_cxp WHERE EMPRESA = '" + #[User::cia] + "'"
sqlCommand1 = new SqlCommand("INSERT INTO dbo.Orders(Title,Seats,Payment,DateNTime)"+
"VALUES ('"+ movieName+"',"+numTickets+",'"+creditCardType+"',"+DateTime.Now+")", sqlConnection1);
sqlCommand1.Connection.Open();
sqlCommand1.ExecuteNonQuery();
sqlCommand1.Connection.Close();
No idea what's wrong with this piece of code. Title and Payment are stored as nvarchar types, Seats as an int and DateNTime as DateTime.
Can someone help me with this?
Thanks in advance
Need quotes for dates as well:
,'" + DateTime.Now.ToString("yyyyMMdd") + "')"
But this is very dangerous code you know. You really should use parametrized query for such things!
You will be in trouble if user enters in Title textbox something like this:
some text', 1, 1, '20100101'); drop table dbo.Orders--
And you are fired the same day.
Very likely the error lies here:
... ,"+DateTime.Now+")"
You must make sure, that the string expression for DateTime.Now is parseable in SQL.
Do not put your values into the SQL comman (read about SQL injection)
Read about parameters and how to pass them
Never rely on culture dependant date-time-formats... (read about ISO8601 or ODBC)
Guessing this is called from c# code, you should use parameters instead of concatenating strings into sql statements.
This will both protect you from sql injection attacks and fix your syntax error:
This code should probably work for you, though it's written right here and I didn't test it:
using (var sqlConnection1 = new SqlConnection("ConnectionString"))
{
using (var sqlCommand1 = new SqlCommand("INSERT INTO dbo.Orders(Title,Seats,Payment,DateNTime)" +
"VALUES (#movieName, #numTickets, #creditCardType, #DateTime.Now)", sqlConnection1))
{
sqlCommand1.Parameters.Add("#movieName", SqlDbType.VarChar).Value = movieName;
sqlCommand1.Parameters.Add("#numTickets", SqlDbType.VarChar).Value = numTickets;
sqlCommand1.Parameters.Add("#creditCardType", SqlDbType.Int).Value = creditCardType;
sqlCommand1.Parameters.Add("#movieName", SqlDbType.DateTime).Value = DateTime.Now;
sqlCommand1.Connection.Open();
sqlCommand1.ExecuteNonQuery();
}
}
Try to use following
sqlCommand1 = new SqlCommand("INSERT INTO dbo.Orders(Title,Seats,Payment,DateNTime)"+
"VALUES ('"+ movieName+"',"+numTickets+",'"+creditCardType+"','"+DateTime.Now+"')", sqlConnection1);
sqlCommand1.Connection.Open();
sqlCommand1.ExecuteNonQuery();
sqlCommand1.Connection.Close();
Even after that modification, if you are getting error, please tell datatype of Title,Seats,Payment,DateNTime
You have format date part also.
sqlCommand1 = new SqlCommand("INSERT INTO dbo.Orders(Title,Seats,Payment,DateNTime)"+
"VALUES ('"+ movieName+"',"+numTickets+",'"+creditCardType+"','"+DateTime.Now.ToString("yyyyMMdd")+"')", sqlConnection1);
sqlCommand1.Connection.Open();
sqlCommand1.ExecuteNonQuery();
sqlCommand1.Connection.Close();
I have the following piece of code:
String sql = "SELECT * FROM users WHERE email = " + email;
prestat = DBConnection.prepareStatement(sql);
rs = prestat.executeQuery();
boolean isEmpty = !rs.first();
if (isEmpty) {
// Special marker for nonexistent user
return "$null";
} else if (password.equals(rs.getString(2))) {
String uuid = UUID.randomUUID().toString();
// Here I want to insert the UUID into the database
}
Considering that I have already searched the database, I'm wondering if there is a way I can get the row number/position,and use it to update the UUID column, hence preventing another DB search.
It's not clear what you are trying to do here, and it doesn't really seem you understand what goes on. For example, when using a prepared statement, one doesn't feed it with two concatenated strings, but instead does:
PreparedStatement stmt =
conn.prepareStatement("SELECT * FROM foo WHERE bar = ?");
stmt.setString(1, "Hello World!");
Then, if you really want to avoid the double search, you can simply assume an optimistic point of view:
UPDATE users SET uuid = ? WHERE email = ? AND password = ?
Ensure that the email is unique, by the way. Also, maybe you already do it, but don't save plaintext passwords in the db. Use cryptographic hashes instead, and salt them.
Since you specify that your backend is Apache Derby, maybe this guide can help you solve your problem (it's 100% Java but not truly portable because of different backends may not implement all of the required features). Basically, you pass two flags when preparing the statement:
Statement stmt = con.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
ResultSet res = stmt.executeQuery("SELECT * FROM users WHERE email = ?");
and then you have a ResultSet backed by an updateable cursor, so you can call:
res.updateString("uuid", uuid);
res.updateRow();
I think this may avoid the additional search, however I didn't test it and cannot say if there's a real performance gain. Sounds like premature optimization, though.
well you could simply replace
prestat = DBConnection.prepareStatement("SELECT * FROM users WHERE email =" + email);
by
prestat = DBConnection.prepareStatement("Update users set uuid = '" + uuid + "' WHERE email =" + email);
And of course execute.
I have been able to link PostgreSQL to java. I have been able to display all the records in the table, however I unable to perform delete operation.
Here is my code:
con = DriverManager.getConnection(url, user, password);
String stm = "DELETE FROM hostdetails WHERE MAC = 'kzhdf'";
pst = con.prepareStatement(stm);
pst.executeUpdate();
Please note that MAC is a string field and is written in capital letters. This field does exist in the table.
The error that I am getting:
SEVERE: ERROR: column "mac" does not exist
When it comes to Postgresql and entity names (Tables, Columns, etc.) with UPPER CASE letters, you need to "escape" the word by placing it in "". Please refer to the documentation on this particular subject. So, your example would be written like this:
String stm = "DELETE FROM hostdetails WHERE \"MAC\" = 'kzhdf'";
On a side note, considering you are using prepared statements, you should not be setting the value directly in your SQL statement.
con = DriverManager.getConnection(url, user, password);
String stm = "DELETE FROM hostdetails WHERE \"MAC\" = ?";
pst = con.prepareStatement(stm);
pst.setString(1, "kzhdf");
pst.executeUpdate();
I am looking for backdoors in various softwares and wondering if the following code is vulnerable to a sql injection.
There's an email field with the following validation expression. (ASPX/CS)
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">
Is it possible to exploit the above to drop a table for example or do anything malicious using a SQL injection?
Thanks
Regards
EDIT 1: People have asked me how this was implemented —
SqlConnection conn = new SqlConnection(snpConnectionString);
SqlCommand command = conn.CreateCommand();
conn.Open();
command.CommandText = "INSERT INTO TABLE_ VALUES ('" + TextBoxFN.Text + "','" + TextBoxLN.Text + "','" + sb1.ToString() + "','" + TextBoxEA.Text + "','" + sb.ToString() + "',0,'" + DateTime.Now + "')";
try{
SqlDataReader reader = command.ExecuteReader();
}
catch
{
Response.Redirect("Error.aspx", true);
}
TextBoxEA.text corresponds to the email address.
Regular expression validation is great for the UI or business layer to check user input to prevent errors.
It is less great for preventing SQL injection.
If the code does not use parameterized queries, it is vulnerable either now, or later after someone makes a minor error updating the regular expression to conform to a new business requirement.
It is best to use parameterized queries like Eric stated, but looking at the regex only the following characters are valid
A-Za-z0-9_-+.'
Without a space I don't think they could inject SQL, but if it was me I'd still make sure to use parameterized queries to be safe.