I have the following string which holds the query I want to execute:
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " set bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
I get an Update statement syntax error but I dont see where is the error. Any help is appreciated.
columns "descripcion" and "bodega" are text type columns.
Well it's probably because you've got multiple set parts instead of using comma separation, and potentially because you don't have quotes around the codigo value (if that's another string)... but I'd strongly advise you not to create SQL like this anyway, with values directly in the SQL.
Instead, use a prepared statement:
String sql = "UPDATE inventario set descripcion=?, bodega=? where codigo=?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, descripcion);
st.setString(2, bodega);
st.setString(3, codigo);
Using prepared statements has three immediate benefits:
It avoids SQL injection attacks (think about what happens if your description has a quote in it)
It separates code (SQL) from data (the values)
It means you avoid conversions for types like datetime, where going via a string representation is a huge potential source of error
Remove extra SET on your query.
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
but that query is vulnerable with SQL Injection. Please parameterize your query.
Example,
String query = "UPDATE inventario" +
" set descripcion = ?, bodega = ? " +
" where codigo = ?";
PreparedStatement prep = connection.prepareStatement(query);
prep.setString(1, descripcion);
prep.setString(2, bodega);
prep.setInt(3, codigo);
prep.executeUpdate();
SET keyword is needed only once. Multiple columns that are being updated should be separated by commas, as in the below statement.
query = "UPDATE inventario"
+ " set descripcion = '" + descripcion + "',"
+ " bodega = '" + bodega + "'"
+ " where codigo = " + codigo;
BTW, it is highly recommended to use PreparedStatement for such operations instead of forming the query like this to avoid SQL Injection attacks.
query = "UPDATE inventario"
+ " set descripcion = ?, bodega = ? "
+ " where codigo = ?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, descripcion);
ps.setString(2, bodega);
ps.setInt(3, codigo);
int updateCount = ps.executeUpdate();
Related
I am trying to make a connection to a database and then run an INSERT INTO query, but when the code runs, i get the error: com.microsoft.sqlserver.jdbc.SQLServerException: Invalid column name 'BLUE'.
As you can see in my code below, i give "BLUE" as an value instead of an column name. Does anyone knows what i am doing wrong? p.s. color is an Enum, all the other values are doubles.
String query = "INSERT INTO [oval] " +
"(anchorX, anchorY, width, height, weight, color) VALUES " +
"(" + drawingItem.getAnchor().getX() +
", " + drawingItem.getAnchor().getY() +
", " + drawingItem.getWidth() +
", " + drawingItem.getHeight() +
", " + ((Oval) drawingItem).getWeight() +
", " + drawingItem.getColor().toString() + ")";
initConnection();
Statement myStmt = con.createStatement();
rowsAffected = myStmt.executeUpdate(query);
closeConnection();
EDIT ANSWER:
String query = "INSERT INTO [oval] VALUES (?,?,?,?,?,?)";
initConnection();
PreparedStatement myPrepStmt = con.prepareStatement(query);
myPrepStmt.setDouble(1, drawingItem.getAnchor().getX());
myPrepStmt.setDouble(2, drawingItem.getAnchor().getY());
myPrepStmt.setDouble(3, drawingItem.getWidth());
myPrepStmt.setDouble(4, drawingItem.getHeight());
myPrepStmt.setDouble(5, ((Oval)drawingItem).getWeight());
myPrepStmt.setString(6, drawingItem.getColor().toString());
rowsAffected = myPrepStmt.executeUpdate();
closeConnection();
As suggested, use parametrized query to prevent SQL injection. As for the problem in hand, you must use single quote to each string values.
Ex:
"('" + drawingItem.getAnchor().getX() +
"', '" +
Correct way would be:
String query = "INSERT INTO [oval] " +
"(anchorX, anchorY, width, height, weight, color) VALUES " +
"(?, ?, ?, ?, ?, ?)";
initConnection();
int i = 1;
Statement myStmt = con.prepareStatement(query);
myStmt.setInt(i++, drawingItem.getAnchor().getX());
myStmt.setInt(i++, drawingItem.getAnchor().getY());
myStmt.setString(i++, drawingItem.getWidth());
myStmt.setString(i++, drawingItem.getHeight());
myStmt.setFloat(i++, ((Oval) drawingItem).getWeight());
myStmt.setString(i++, drawingItem.getColor().toString());
rowsAffected = myStmt.executeUpdate();
Basically I'm trying to update a Database table with the values of a getSelectRow. As you can see, the query finds the correct data, but has huge issues when actually trying to add it to the database.
The error is in the SQL syntax, but I don't know where I'm going wrong. Please Help.
This is the query that it executes, but I have no idea why it isn't updating the table.
INSERT INTO customerdetails
FName = 'Tim'
AND SName = 'Cooley'
AND Address = '52 Buckminster Drive Dorridge Solihull West Mids'
AND Postcode = 'B93 8PG'
Java code:
private void sendBtnMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
int insertRow = newOrderTbl.getSelectedRow();
int col2 = 0;
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = '" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "AND SName = '" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "AND Address = '" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "AND Postcode = '" + newOrderTbl.getValueAt(insertRow, col2+3) +"'";
System.out.println(sql3);
try{
pst = conn.prepareStatement(sql3);
pst.executeUpdate(sql3);
JOptionPane.showMessageDialog(null, "Deleted");
CustomerTable();
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
To begin with, your SQL syntax is wrong (at least that it is a non-standard SQL syntax for your database engine). Second, your code is vulnerable to SQL Injection attack.
In order to solve both problems, you should use a PreparedStatement (that you're doing in the wrong way). A basic example from your code:
String sql = "INSERT INTO customerdetails (FName, SName, Address, Postcode) VALUES (?, ?, ?,?)";
PreparedStatement pst = conn.prepareStatemtnt(sql);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
Assuming your SQL syntax will work, then you should pass the values as parameters, similar to the previous example:
String sql3 = "INSERT INTO customerdetails VALUES "
+ "FName = ?"
+ "AND SName = ?"
+ "AND Address = ?"
+ "AND Postcode = ?"
pst = conn.prepareStatement(sql3);
pst.setString(1, newOrderTbl.getValueAt(insertRow, col2));
pst.setString(2, newOrderTbl.getValueAt(insertRow, col2+1));
pst.setString(3, newOrderTbl.getValueAt(insertRow, col2+2));
pst.setString(4, newOrderTbl.getValueAt(insertRow, col2+3));
pst.executeUpdate();
//rest of code...
for update statement it will be -
String sql3 = "INSERT INTO customerdetails(FName,SName,Address,Postcode) VALUES "
+ " '" + newOrderTbl.getValueAt(insertRow, col2) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+1) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+2) +"',"
+ " '" + newOrderTbl.getValueAt(insertRow, col2+3) + "')";
Also you should use PreparedStatement for this.
Thanks
Please change it to
String sql3 = "INSERT INTO customerdetails(FName,SName,Address,Postcode) VALUES ("
+ "'" + newOrderTbl.getValueAt(insertRow, col2) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+1) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+2) +"'"
+ "'" + newOrderTbl.getValueAt(insertRow, col2+3) +"')";
The generated insert statement in your code seems invalid. Please see SQL Insert Statement for more information
Also, the better approach would be to create a dedicated Serverside DAO class to handle database operations.
I am writing the following SQL query in my Java program
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from "
+ "student where ID =" + ID + " or FirstName=" + firstName + ";");
However, I am getting the following error:
use the right syntax for FirstName="+Parker
How is this caused and how can I solve it?
You should take advantage of prepared statements by making use of prepared statements parameters. This way, you can set your parameters pragmatically using setters.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
Here is a snippet from the Oracle docs:
PreparedStatement updateSales = null;
String updateString = "update " + dbName + ".COFFEES " + "set SALES =
? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
updateSales.**setInt**(1, e.getValue().intValue());
updateSales.**setString**(2, e.getKey());
Just make sure you set the statements *in order a*s the sql query.
Use a PreparedStatement like this:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from student where ID = ? or FirstName = ?");
pre.setInt(1, ID);
pre.setString(2, firstName);
I haven't used sql in Java, but my guess is it is because you don't have single quotes around first name. You want:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from " + "student where ID =" + ID + " or FirstName='" + firstName + "';");
emphasis:
... FirstName='" + firstName + "';");
1.How do I use PrepareStatement for familyname and givenname?
2.Also, how do I case insensitive search by familyname or givenname?
String query ="SELECT agent.familyname, agent.givenname" +
" FROM agent" +
" WHERE agent.agentid = piececreation.agentid" +
" AND (LOWER(familyname) = '"+agent_lastname+"' OR LOWER(givenname) = '"+agent_name+"') ORDER by familyname";
PreparedStatement pst = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
pst.setString(1, agent_lastname);
pst.setString(2, agent_name);
// Executing the insert
pst.executeUpdate();
Make familyName or givenName to lowercase too since you are already using LOWER DB API
String query ="SELECT agent.familyname, agent.givenname" +
" FROM agent" +
" WHERE agent.agentid = piececreation.agentid" +
" AND (LOWER(familyname) = '"+agent_lastname.toLowerCase()+"' OR LOWER(givenname) = '"+agent_name.toLowerCase()+"') ORDER by familyname";
When you are using PreparedStatement dont append values directly in your SQL, if you do that you are prone to SQL Attack instead parametrize your values.
String query =
"SELECT agent.familyname, agent.givenname"
+ " FROM agent"
+ " WHERE agent.agentid = ?"
+ " AND ("
+ " LOWER(familyname) = ? OR LOWER(givenname) = ?"
+ ") "
+ " ORDER by familyname";
pst.setInt(1, piececreation.agentid);
pst.setString(2, agent_lastname.toLowerCase());
pst.setString(3, agent_name.toLowerCase());
Then set values calling appropriate setXXX methods as defined here.
You can read tutorial here
You can use the following query for caseinsensetive search.
String query =
"SELECT agent.familyname, agent.givenname"
+ " FROM agent"
+ " WHERE agent.agentid = ?"
+ " AND ("
+ " familyname ilike ? OR givenname ilike ?"
+ ") "
+ " ORDER by familyname";
pst.setInt(1, piececreation.agentid);
pst.setString(2, agent_lastname.toLowerCase());
pst.setString(3, agent_name.toLowerCase());
I get the following exception,
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "80" at line 1, column 1100.
when I try to insert like the following! Any idea what this could mean??!
String insertString = "insert into queries (data_id, query, "
+ "query_name, query_file_name, status) values(" + currentDataID + ", '"
+ params[1] + "', '" + params[2] + "', '"
+ params[3] + "', '" + params[4] + "')";
try {
Statement stmt = dbconn.createStatement();
stmt.execute(insertString, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = stmt.getGeneratedKeys();
if (rs != null && rs.next()){
currentDataID = (int) rs.getLong(1);
}
} catch (SQLException ex) {
}
Table definition,
CREATE TABLE queries (query_id INT not null primary key GENERATED "
+ "ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), data_id "
+ "INTEGER not null, foreign key (data_id) references data "
+ "(data_id), query LONG VARCHAR, query_name VARCHAR(150), "
+ "query_file_name VARCHAR(150),status VARCHAR(20))
Try this approach with a prepared statement:
String insert = "INSERT INTO queries (data_id, query, query_name," +
" query_file_name, status) VALUES (?,?,?,?,?)";
PreparedStatement stmt = dbconn.prepareStatement(insert, Statement.RETURN_GENERATED_KEYS);
// Why do you set this if you want the DB to generate it?
stmt.setInt(1, currentDataID); // or setLong() depending on data type
stmt.setString(2, params[1]); // I assume params is a String[]
stmt.setString(3, params[2]);
stmt.setString(4, params[3]);
stmt.setString(5, params[4]);
stmt.execute();
ResultSet rs = stmt.getGeneratedKeys();
if (rs.next()) {
// if it's an int, avoid the cast and use rs.getInt(1) instead
currentDataID = (int) rs.getLong(1);
}
I don't understand why you set the data_id while the later code expects the database to generate it... Your table definition would help.
This is probably happening because one of your params[] contains a quote character.
This problem is exactly why you shouldn't create SQL expressions like this, but should instead use a PreparedStatement. Please read up on SQL injection.