MySQL Statement error in JSP - mysql

I have an issue with an sql statement and i dont know how to handle it. Here is the problem:
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")')";
The values are obtained from the post form which contains free text. The problem is, whenever a user enters characters like ', i will get an error because that tells the compiler that the value is over here(i suppose) and now look for the next value. I don't know how to include these characters and send them to database without having an error. Any help would be appreciated. Thank you.

The character ' is used to surround literals in MySQL. And if any data contains such character as part of it, we have to escape it. This can be done using Prepared Statement in Java.
Change your query code accordingly.
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`)
VALUES ( ?, ?,? )";
Now define a PreparedStatement instance and use it to bind values.
PreparedStatement pst = con.prepareStatement( query );
pst.setString( 1, session.getAttribute("id") );
pst.setString( 2, request.getParameter("RunningProjects") );
pst.setString( 3, request.getParameter("MainOrders") );
int result = pst.executeUpdate();
And, I suggest use of beans to handle business logic.

change
query = "INSERT INTO `mmr`(`userID`, `RunningProjects`, `MainOrders`) VALUES ("
+ session.getAttribute("id")
+ ",'"
+ request.getParameter("RunningProjects")
+ "','"
+ request.getParameter("MainOrders")
+ "')";

I think you are using normal statement in your JDBC code. Instead, I would suggest you to use Prepared statement. Prepared statement is generally used to eliminate this kind of problem and caching issue. If you will use prepared statement I think your problem will be solved

Related

SQL parametric columns in ASP.NET

Why can you not use parameters in an SQL statement as the column name? I found that out after two hours of thinking what the problem could be. The only way it seemed possible was by doing it in a way it could be vulnerable to SQL injections (which for me wasn't a problem because the parameters are generated serverside).
This works:
string cmdgetValues = "SELECT " + column + " FROM user WHERE " + filterColumn + " = #filter";
MySqlCommand getValues = new MySqlCommand(cmdgetValues, connectionDB);
getValues.Parameters.AddWithValue("#filter", filterValue);
This doesn't work:
string cmdgetValues = "SELECT #column FROM user WHERE #filterColumn = #filter";
MySqlCommand getValues = new MySqlCommand(cmdgetValues, connectionDB);
getValues.Parameters.AddWithValue("#column", column);
getValues.Parameters.AddWithValue("#filterColumn", filterColumn);
getValues.Parameters.AddWithValue("#filter", filterValue);
Why is this? And is it intended?
Because select columns are fundamental query
You can't parameterise the fundamental query, so you have to build the query at the code.
If you want to decide the query columns runtime maybe you can try to use Prepared SQL Statement Syntax in Mysql.

How to insert file path into mysql table using nodejs

I am currently using mutler to upload the files to the server. Below is my query:
var insertSQL = "INSERT INTO ic_photos (icFrontURL,icBackURL,selfieURL,customer_id) VALUES ('" + frontICPath + "','"+backICPath + "','" + selfiePath + "','" + customerID + "')";
Console.log returns
"INSERT INTO ic_photos (icFrontURL,icBackURL,selfieURL,customer_id) VALUES ('public\images\frontIC_1526709299585_potato.png','public\images\backIC_1526709299595_potato2.jpg','public\images\selfie_1526709299596_potato3.jpg','41')"
But when it goes into mysql table, it shows the following value:
'publicimagesfrontIC_1526709040516_potato.png'
The slashes are missing. How can I fix this when I make the insert query ?
This replaces the backslash with two backslashes. When it got inserted into the table, it will become one backslash
frontICPath = frontICPath.replace(/\\/g, "\\\\");
In most, if not all string-based interpretation environments, a backslash is considered a special character. To use a backslash explicitly, please use: "\\".
The two slashes above consist of 4 slashes in total through the text editor.

Multi tables update using javafx and Mysql

I have to update a customer information that are spread over 4 Mysql tables. I created 1 Customer class. when I first add the information it is added to an observable list that populate a table, and by clicking on a selected row the information are displayed in textboxes to edit, but the updates are not being saved into the MySQL tables. Can you tell if it is from this part of code or is it coming from somewhere else in the program. What is wrong with my code ?
public void updateCustomer(Customer selectedCustomer, String user, LocalDateTime timePoint) throws Exception{
String query = "UPDATE customer, address, city, country"
+ " SET customer.customerName = '"+selectedCustomer.getCustomerName()+"', customer.lastUpdate = '" +timePoint+"', customer.lastUpdateBy = '"+user+ "', "
+ " address.address = '" +selectedCustomer.getAddress()+ "', address.address2 = '" +selectedCustomer.getAddress2()+ "', address.postalCode = '" +selectedCustomer.getPostalCode()+ "', address.phone = '" +selectedCustomer.getPhone()+ "', address.lastUpdate='" +timePoint+ "', address.lastUpdateBy = '" +user+ "', "
+ " city.city = '"+selectedCustomer.getCity()+"',city.lastUpdate='"+timePoint+"',city.lastUpdateBy = '"+user+ "', "
+ " country.country = '"+selectedCustomer.getCountry()+"',country.lastUpdate ='"+timePoint+"',country.lastUpdateBy = '"+user+ "' "
+ " WHERE customer.customerId = " +selectedCustomer.getCustomerId()+ " AND customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId " ;
statement.executeUpdate(query);
}
What I usually do is:
Create my data class.
Create load and save methods on my DB class.
Set up the FXML so that the TableColumns show the right information from the data class
Get the data into an ObservableList from the database (I like to use Derby but that shouldn't make a difference) and put that into the table.
Add a listener to the selection model so that when the selected item in the table changes, the selected item is referenced by another variable (say "selectedCustomer" and that variable's data is shown into the editable textfields or comboboxes or whatever. Note that I don't use bindings when showing the selectedCustomer in the textboxes. I just use plain setTexts.
When the user clicks on Save or something, the data in the textfields are set into the selectedCustomer (for example, selectedCustomer.setName(nameText.getText());)
I call the database class' save method (for example, DB.save(selectedCustomer); )
That should do the trick! Never failed me yet.
However, I may be at fault here, since I couldn't be bothered to read your SQL statement. Please, for goodness sake, learn to use PreparedStatements! First, I don't really understand how your table is set up, so I can't really comment, but it's really hard to understand. However, if I were to take a wild guess, I think the problem may have something to do with this part here:
WHERE ... AND customer.addressId = address.addressId AND address.cityId = city.cityId AND city.countryId = country.countryId
I don't understand how that part works--either that SQL statement does not make sense or my SQL needs practice (probably the latter).
Since you use MySQL, how about you use a manager (such as PHPMyAdmin or since you are using Java, SQuirreL) to try executing your SQL statement manually and see what happens? If you enter the SQL statement and nothing changed (when there should be) then your SQL statement is at fault.

Does PreparedStatement convert empty strings to null?

I'm working with MySQL and their last available JDBC driver, on a User table with NOT NULL constraints on all its fields, which are id, name, password and email.
In my Java EE application, I first called a simple Statement this way :
statement = connection.createStatement();
statement.executeUpdate( "INSERT INTO User (name, password, email) "
+ "VALUES ('" + paramName + "', '" + paramPassword + "', '" + paramEmail + "');" );
Where paramName, paramPassword and paramEmail are strings. I passed empty strings to this request, and a new line with empty values got successfully inserted in the table, since MySQL considers empty strings different than null entries.
Then, I used a PreparedStatement instead :
preparedStatement = connection.prepareStatement( "INSERT INTO User (name, password, email) VALUES(?, ?, ?);" );
preparedStatement.setString( 1, paramName );
preparedStatement.setString( 2, paramPassword );
preparedStatement.setString( 3, paramEmail );
preparedStatement.executeUpdate();
But this time, when I passed empty strings to the request, I got the following error :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'name' cannot be null
So here's my question : does the PreparedStatement, or maybe its setString() method, convert empty strings to null values? I looked it up and didn't find any information about this behavior in the javadoc.
The documentation of java.sql.PreparedStatatement didn't say anything about this in the method setString. I take a look at the sources of the MySQL ConnectorJ and I didn't find anything too. Are you sure that your String is not null?
The answer is NO. Please make sure that the value of your parameters are not null. Maybe your variable paramName is NULL.

how to use SQL wildcard % with Queryset extra>select?

I'm using the extra() modifier in a view.
(See http://docs.djangoproject.com/en/1.1/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none )
Here's the the code:
def viewname(request)
...
exact_matchstrings=[]
exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + "')")
exact_matchstrings.append("(accountprofile.first_name LIKE '" + term + '\%' + "')")
extraquerystring = " + ".join(exact_matchstrings)
return_queryset = return_queryset.extra(
select = { 'match_weight': extraquerystring },
)
The two append statements above are almost completely alike except that the second adds a % SQL wildcard character. This is causing an error; the statement without the % causes no problems. What's going on with the %? I'm surprised that django thinks this character is not defined, since it's in SQL specification. For example, the following SQL statement executes just fine:
select (first_name like "Car") + (first_name like "Car%") from accountprofile;
But trying to run it via the extra() modifier in my view code and evaluating the resulting queryset gives me an error. I think "%" needs to be escaped, so I tried that already. Any ideas?
Just ran into this issue ourselves doing a extra query with LIKE. To escape a % you need to do %%
Percentage sign not working
It looks like you are missing some quotes from the 2nd string. And I'm not sure that you need to escape the percent (%) unless this is required by django.
_matchstrings.append("(accountprofile.first_name LIKE '" + term + "%" + "')")