Just looking for a little help,
Created an application in JAVA and using a jTable to gather data from myphp database, I am using Insert, update and delete SQL commands so the user is able to manipulate data in the table.
Delete works perfectly, however I am having some trouble with my update and insert commands, just wondering if anyone can see if im using the ("'+) incorrectly, im not as eagle eyed as someone more experienced so just seeing if anyone can shed some light :)
Thanks!
INSERT CODE :
String query = "INSERT INTO `supplier`(`Company Name`, `Contact`, `Address`, `Postcode`, `Phone`) VALUES ('"+jTextField_SupplierCompany.getText()+"','"+jTextField_SupplierContact.getText()+"',"+jTextField_SupplierAddress.getText()+"','"+jTextField_SupplierPostcode.getText()+"',"+jTextField_SupplierPhone.getText()+")";
UPDATE CODE:
String query = "UPDATE `supplier` SET `Company Name`='"+jTextField_SupplierCompany.getText() + "',`Contact`='"+jTextField_SupplierContact.getText() + "',`Address`="+jTextField_SupplierAddress.getText() + "',`Postcode`="+jTextField_SupplierPostcode.getText() + "',`Phone`="+jTextField_SupplierPhone.getText() + " WHERE `ID` = "+jTextField_SupplierID.getText();
ERROR:
The error is throwing is the misuse of the WHERE clause in the "UPDATE" statement... May be obvious to some however cant get my head around it.
To avoid these type of syntax errors, or any SQL Injection, you can use PreparedStatement instead, it is so simple and so helful :
String query = "INSERT INTO `supplier`(`Company Name`, `Contact`, `Address`, `Postcode`, `Phone`) "
+ "VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstm = conn.prepareStatement(query)) {
pstm.setString(1, jTextField_SupplierCompany.getText());
pstm.setString(2, jTextField_SupplierContact.getText());
pstm.setString(3, jTextField_SupplierAddress.getText());
pstm.setString(4, jTextField_SupplierPostcode.getText());
pstm.setString(5, jTextField_SupplierPhone.getText());
pstm.executeUpdate();
}
Your error happen because you forgot to close your String with '' check your query and you will see :
+"', " + jTextField_SupplierAddress.getText() + "'
//--^--------------------------------------------^
You Missed the Single quote in query
use this for insert
String query = "INSERT INTO supplier(Company Name, Contact, Address, Postcode, Phone) VALUES ('"+jTextField_SupplierCompany.getText()+"','"+jTextField_SupplierContact.getText()+"','"+jTextField_SupplierAddress.getText()+"','"+jTextField_SupplierPostcode.getText()+"','"+jTextField_SupplierPhone.getText()+"')";
Use this for update
String query = "UPDATE 'supplier' SET 'Company Name='"+jTextField_SupplierCompany.getText() + "',Contact='"+jTextField_SupplierContact.getText() + "',Address='"+jTextField_SupplierAddress.getText() + "',Postcode='"+jTextField_SupplierPostcode.getText() + "',Phone='"+jTextField_SupplierPhone.getText() + "' WHEREID` = '"+jTextField_SupplierID.getText()+"'";
Related
I'm looking for help to insert json data into postgres table using java program. I have tried with following code but cannot find any data is inserted in to the table. I have very little experience in programming. Can some one help me to modify my program to make it work?
here is my code.
enter code here stmt = c.createStatement();
String sql = "CREATE TABLE jason " +
"(ID INT NOT NULL," +
" NAME json NOT NULL)";
stmt.executeUpdate(sql); //updates the table
//json data----------------
String[] MESSAGE = {"{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }"};
sql = "INSERT INTO jason (ID,NAME) "
+ "VALUES (1,::MESSAGE );";
stmt.executeUpdate(sql);
You have problem with syntax here, please read this instruction: https://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html
It's should be:
PreparedStatement pstmt = con.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1, ?1);");
pstmt.setString(1, yourJsonString)
To use parameters in a statement, you need to use a prepared statement:
java.sql.PreparedStatement stmt = conn.prepareStatement("INSERT INTO jason (ID,NAME) VALUES (1,?)" );
stmt.setString(1, "{\"customer_name\": \"John\", \"items\": { \"description\": \"milk\", \"quantity\": 4 } }");
stmt.executeUpdate();
I have written this code to add stuff to the database, however, when I try running it it does not work, i've been looking for ways to do it, but i just cant seem to find the solution, can anyone help?
String mySQL ="INSERT INTO Measurement (Level, Time, Date, TankID)"+"VALUES (textField1, currentTime,currentDate,(SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
stmt.executeUpdate(mySQL);
Both your SQL and prepared statement are malformed. Try using an INSERT INTO ... SELECT here:
String sql = "INSERT INTO Measurement (Level, Time, Date, TankID) ";
sql += "SELECT ?, ?, ?, TankID ";
sql += "FROM Tanks ";
sql += "WHERE TankName = '2' AND Site_ID = '1'";
stmt.setString(1, textField1);
stmt.setString(2, currentTime); // not sure about the type here
stmt.setString(3, currentDate); // also not sure about the type
stmt.executeUpdate();
Note that I am unsure about both the Java and SQL binding types of the columns for currentTime and currentDate. If not string, then the above would have to change slightly.
You should be using PreparedStatement to properly set the first parameter of the insert query and check the documentation of your DB server to use existing functions to get current time and date.
For example, mySQL has functions CURDATE() and CURTIME()
String query = "INSERT INTO Measurement (Level, Time, Date, TankID) "
+ "VALUES (?, CURTIME(), CURDATE(), (SELECT TankID FROM Tanks WHERE TankName = '2' AND Site_ID = '1'))";
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.setString(1, textField1); // could be textField1.getText() or textField1.getValue()
statement.executeUpdate();
}
Based on your Database type change the connection details
Follow this Link for creating JDBC Connection and Inserting data
If you did the above steps please ignore this..
I'm working in one quiz game. There is question maker window. Which works good for saving question. But when want update one of text Field and press save, than error is happening. something is wrong with syntax?!
void insertCell(String tableNamer, String column, String value, int id) throws ClassNotFoundException, SQLException{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:file:C:/Users/Juris Puneiko/IdeaProjects/for_my_testings/src/sample/DB/Questions/For_Private/Easy", "Juris", "1");
PreparedStatement ps = conn.prepareStatement("UPDATE ? SET ? = ? where ID = ?");
ps.setString(1, tableNamer);
ps.setString(2, column);
ps.setString(3, value);
ps.setInt(4, id);
ps.executeUpdate();
ps.close();
conn.close();
}
org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "UPDATE ?[*] SET ? = ? WHERE ID = ? "; expected "identifier"; SQL statement:
UPDATE ? SET ? = ? where ID = ? [42001-196]
What is this >>> [*]?
What does it mean?
String sql = "UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, value);
ps.setInt(2, id);
ps.executeUpdate();
ps.close();
conn.close();
The placeholders can only be used for values in most SQL databases, not for identifiers like table or column names:
"UPDATE myTable SET myCol = ? where ID = ?" -- OK
"UPDATE ? SET ? = ? where ID = ?" -- not OK
The reason is that those parameters are also used for prepared statements, where you send the query to the database once, the database "prepares" the statement, and then you can use this prepared statement many times with different value parameters. this can improve DB performance because DB can compile and optimize the query and then use this processed form repeatedly - but to be able to do this, it needs to know names of the tables and columns involved.
To fix this, you only leave the ?s in for the values, and you concatenate the tableNamer and column manually:
"UPDATE " + tableNamer + " SET " + column + " = ? where ID = ?"
Keep in mind though that by doing this, tableNamer and column are now potentially vulnerable to SQL injection. Make sure that you don't allow user to provide or affect them, or else sanitize the user input.
I'm working with a MySQL-Server and I'm trying to select an ID from another table and insert that ID in a table but it doesn't work all the time.
Code:
public void submit() throws Exception {
Connection connection = getConnection();
Statement stmt = connection.createStatement();
Statement stmt1 = connection.createStatement();
ResultSet asset_id = stmt.executeQuery("SELECT id FROM cars.asset_type WHERE asset_type.name =" + "'" + sellables.getValue()+ "'");
while (asset_id.next()) {
System.out.println(asset_id.getInt("id"));
}
double value = parseDouble(purchased.getText());
System.out.println(value);
LocalDate localDate = purchased_at.getValue();
String insert = "INSERT INTO asset (type_id, purchase_price, purchased_at) VALUES ('"+ asset_id + "','" + value +"','" + localDate +"')";
stmt1.executeUpdate(insert);
}
I keep getting the same error message.
Caused by: java.sql.SQLException: Incorrect integer value: 'com.mysql.cj.jdbc.result.ResultSetImpl#1779d92' for column 'type_id' at row 1
There's no value in doing two client/server roundtrips in your case, so use a single statement instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
If you really want to insert only the last ID from your SELECT query (as you were iterating the SELECT result and throwing away all the other IDs), then use this query instead:
INSERT INTO asset (type_id, purchase_price, purchased_at)
SELECT id, ?, ?
FROM cars.asset_type
WHERE asset_type.name = ?
ORDER BY id DESC -- I guess? Specify your preferred ordering here
LIMIT 1
Or with the JDBC code around it:
try (PreparedStatement s = connection.prepareStatement(
"INSERT INTO asset (type_id, purchase_price, purchased_at) " +
"SELECT id, ?, ? " +
"FROM cars.asset_type " +
"WHERE asset_type.name = ?")) {
s.setDouble(1, parseDouble(purchased.getText()));
s.setDate(2, Date.valueOf(purchased_at.getValue()));
s.setString(3, sellables.getValue());
}
This is using a PreparedStatement, which will prevent SQL injection and syntax errors like the one you're getting. At this point, I really really recommend you read about these topics!
I have been struggling with an SQL Delete query. I want it to delete a row, Where 2 conditions are met. The error I am getting says my SQL Syntax is wrong near the end at the last ')'.
String sql = "DELETE FROM course
WHERE (username_entry = " + username +
" AND course_name = " + courseToDelete.toUpperCase() + ")";
My variables have the right values and the data in the database corresponds perfectly.
Here is an example of what your raw query might look like:
DELETE
FROM course
WHERE username_entry = tim AND course_name = chemistry;
Of course, this is not valid SQL, because you are comparing text columns against what will be perceived as other columns called tim and chemistry. You really want the above query to look like this:
DELETE
FROM course
WHERE username_entry = 'tim' AND course_name = 'chemistry';
In other words, you need to compare against properly escaped string literals. But in practice, the best thing to do is to use prepared statements, which handle the formatting automatically:
String sql = "DELETE FROM course WHERE username_entry = ? AND course_name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, courseToDelete.toUpperCase());
ps.executeUpdate();
You need to encapsulate string values into quotes
String sql = "DELETE FROM course
WHERE (username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase() + "')";
But better way is to use prepared statements as they do automatical escape
Did you try to remove the braces after the Where clause.
The query would look like below after the change:
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase()+"'";
You don't have to use any open / close paranthesis for the query as such!
As suggested in the other answers, you don't really need to use the injection of variables but instead, use the PreparedStatement
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete +"'";
Hope this helps!