I am looking the best coding pattern for the below update SQL table with prepared statement in Java.
SQL Table name is table1 and attr1, att2, att3, att4, attr5 and .... in table1.
Currently my pseudo
If (want to update att1 only) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?");
} else if (want to update attr1 & attr2 only) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr2 = ?");
} else if (want to update attr1 & attr2 & attr3) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr2 = ?, attr3 = ?");
} else if (want to udpate attr1 & attr3) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr3 = ?");
} ......
.... else {
Bad Request
}
This above code will make more complex with WHERE SQL condition. I don't like this if - else if - else pattern here because
very hard to maintain.
Yes, I know other options are dynamically generate UPDATE SQL query and use ORM solution.
I believe dynamically generate SQL UPDATE Query logic would become complex.
Please provide any other pattern OR solution which can fit best here.
You could just write one update statement to update all non-key fields and call that each time.
public class MyThing {
private long uniqueID;
private String attr1;
private String attr2;
private String attr3;
// ++ rest of attriutes, getters and setters
}
public MyThing getMyThing(long uniqueID) {
// code to retrieve MyThing from table1, poulating all attributes
}
public void updateMyThing(MyThing myThing) {
PreparedStatement pst = Connection.prepareStatement
(" UPDATE table1 SET attr1 = ?, attr2 = ?, attr3 = ?, attr4 = ?, attr5 = ?" +
" WHERE id = ? );
pst.SetString(1, myThing.getAttr1());
pst.SetString(2, myThing.getAttr2());
pst.SetString(3, myThing.getAttr3());
pst.SetString(4, myThing.getAttr4());
pst.SetString(5, myThing.getAttr5());
pst.SetString(6, myThing.getId());
// etc.
}
So retrieve a MyThing object from the DB. Update whatever attributes you want then call the update method. All attributes updated whether they have changed or not
Related
I have an EMPLOYEE table that has 4 fields; ID, NAME, AGE, SALARY. ID is unique and auto-increment.
Below is the code to insert a row in the table, using Spring's JDBCTemplate. Please suggest, how can I auto increment ID field.
String sql = "insert into employee values (?,?,?,?)"
jdbcTemplate.update( sql, ID, bean.getName(), bean.getAge(), bean.getSalary())
I see, you tag your question Oracle, use Oracle sequence then.
String sql = "insert into Employee values (id_seq.nextval, ?, ?, ?)";
jdbcTemplate.update(sql, bean.getName(), bean.getAge(), bean.getSalary());
Ref: How to create Sequence in Oracle.
Just add following code to your domain:
Ref: http://docs.spring.io/spring/docs/2.5.x/reference/jdbc.html#jdbc-auto-genereted-keys
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps =
connection.prepareStatement(INSERT_SQL, new String[] {"id"});
ps.setString(1, name);
return ps;
}
},
keyHolder);
I have a problem using mysql update in eclipse jsp file.
I just use pstmt.executeUpdate in my jsp file. that's work right.
but when I reuse pstmt.executeUpdate for updating another host's database i can't update mysql data.
when I update second executeUpdate without update's "where" query, it's work right. I can update mysql data.
but only the problem is that when i update executeUpdate with "where", I cannot update the mysql data.
case1(no problem)
use preparedStatement1, update query with 'where' -> OK
use preparedStatement2, update query without 'where' -> OK
case2(problem)
use preparedStatement1, update query with 'where' -> OK
use preparedStatement2, update query with 'where' -> update fail
(and I already test my code in mysql workbench, there is no problem first UPDATE and second UPDATE with 'where'. I have only a problem adding update with 'where' code in my eclipse.)
behind is a my code.
String DB_USER = (String)session.getAttribute("id");
String DB_PASSWORD = (String)session.getAttribute("password");
String DB_HOST = "jdbc:mysql://rds01.********.ap-northeast-2.rds.amazonaws.com:3306/inventory_" + DB_USER + "?useUnicode=true&characterEncoding=euckr";
Connection con;
PreparedStatement pstmt;
String query = "UPDATE inventory_"+DB_USER+" SET "
+ "color1_size1 = ?, color1_size2 = ?, color1_size3 = ?, color1_size4 = ?, color1_size5 = ?, color1_size6 = ?, color1_size7 = ?, color1_size8 = ? "
+ "WHERE NAME = ? AND YEAR = ?";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DB_HOST, DB_USER, DB_PASSWORD);
pstmt = con.prepareStatement(query);
pstmt.setInt(1, color1_size1);
pstmt.setInt(2, color1_size2);
pstmt.setInt(3, color1_size3);
pstmt.setInt(4, color1_size4);
pstmt.setInt(5, color1_size5);
pstmt.setInt(6, color1_size6);
pstmt.setInt(7, color1_size7);
pstmt.setInt(8, color1_size8);
pstmt.setString(9, name);
pstmt.setString(10, year);
pstmt.executeUpdate();
pstmt.close();
con.close();
String query_all = "UPDATE inventory_all SET "
+ "color1_size1 = ?, color1_size2 = ?, color1_size3 = ?, color1_size4 = ?, color1_size5 = ?, color1_size6 = ?, color1_size7 = ?, color1_size8 = ? "
+ "WHERE NAME = ? AND YEAR = ?";
//behind host is another host with upper host.
DB_HOST = "jdbc:mysql://rds01.************.ap-northeast-2.rds.amazonaws.com:3306/inventory_all?useUnicode=true&characterEncoding=euckr";
con = DriverManager.getConnection(DB_HOST, DB_USER, DB_PASSWORD);
pstmt = con.prepareStatement(query_all);
pstmt.setInt(1, color1_size1);
pstmt.setInt(2, color1_size2);
pstmt.setInt(3, color1_size3);
pstmt.setInt(4, color1_size4);
pstmt.setInt(5, color1_size5);
pstmt.setInt(6, color1_size6);
pstmt.setInt(7, color1_size7);
pstmt.setInt(8, color1_size8);
pstmt.setString(9, name);
pstmt.setString(10, year);
//------------upper code is OK, behind code is a problem ----------------
pstmt.executeUpdate();
pstmt.close();
con.close();
} catch(Exception e) {e.printStackTrace();}
Use different PreparedStatement object for second query. Because
a
preparedstatement asks for the sql and immediatly compiles itself.
PreparedStatement pstmt1 = con.prepareStatement(sql1);
pstmt1.executeUpdate();
PreparedStatement pstmt2 = con.prepareStatement(sql2);
pstmt2.executeUpdate();
oh, I know the problem. I add the mysql privilege only update, delete, insert not select in database id.
as I add the 'select' privilege to my id, I can update in my database.
thank for all answer!
I have a date type in oracle and i want insert unix timestamp data into it.
I use this SQL query in PL/SQL which works.
select TO_DATE('19700101','yyyymmdd') + 1413360712/86400 +TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone),1,3))/24 from dual;
the output is right.
2014/10/15 16:11:52
But when i use it in java, the output is different.
String sql = "insert into appliance_application (id, emp_id, typeid, num, spec, action, actiontime, oper_id) VALUES(applianceapplication_seq.nextval, ?, ?, ?, ?, ?, TO_DATE('19700101','yyyymmdd') + 1413360712/86400 +TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone),1,3))/24, ?)";
pstmt = conn.prepareStatement(sql);
for(int i=0; i < list.size(); i++){
Itembean ib = (Itembean)list.get(i);
pstmt.setObject(1, ib.getEmpid());
...
pstmt.setObject(5, ib.getAction());
// pstmt.setLong(6, ib.getActiontime());
// pstmt.setObject(7, ib.getOper_id());
pstmt.setObject(6, ib.getOper_id());
log.info(ib.getActiontime()+ "....");
pstmt.addBatch();
}
...
I check the inserted data and find output is wrong.
2014/10/15 8:11:52
my sessiontimezone is +8.
what's wrong?
Try this code:
public Timestamp parseDateToTimestamp(java.util.Date inDate)
{
if (inDate == null)
return null;
return new java.sql.Timestamp(inDate.getTime());
}
I have a listener that listens a button and takes 3 texts fields from input to execute an update query. I want to execute the update but in the query to pass my local variables(name,city,salary).
What can i do this?
public void actionPerformed(ActionEvent arg0) {
final String name;
final String city;
final String salary;
name = (textFieldName.getText());
city = (textFieldCity.getText());
salary = (textFieldSalary.getText());
System.out.println(salary);
try {
Statement s = connection.createStatement();
s.executeUpdate("INSERT INTO users (name,city,salary) VALUES (name, city,salary)");
I'd go with a PreparedStatement
PreparedStatement s = connection.prepareStatement("INSERT INTO users (name,city,salary) VALUES (?, ?, ?)");
s.setString(1, name);
s.setString(2, city);
s.setString(3, salary);
boolean res = s.execute();
This approach is a bit better, quoting will be automatically managed and will prevent simple SQL Injection.
String insert = "UPDATE PPN_WORKFLOW SET P1_F_Date = ?, SET P1_Completed = ?, SET C2_S_Date = ? WHERE ERF_No = ?";
stmt = conn.prepareStatement(insert);
stmt.setDate(1, date);
stmt.setInt(2, 1);
stmt.setDate(3, date);
stmt.setInt(4, erf_no);
stmt.executeUpdate();
I am trying to update a statement, but I am recieving this error
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in UPDATE statement.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:3148)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedStatement.java:215)
at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPreparedStatement.java:137)
at Mails.MailtoERF.check(MailtoERF.java:60)
at Mails.MailtoERF.main(MailtoERF.java:122)
you can not set like that .you need to change syntax.One time SET is enough
UPDATE PPN_WORKFLOW SET P1_F_Date = ?, P1_Completed = ?..... where condition
You have a SET for each Column name, you need to separate columns with comma only and use SET only once, see syntax here:
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You dont need SET for each column:
MySQL UPDATE SYNTAX:
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
String insert = "UPDATE PPN_WORKFLOW SET P1_F_Date = ?, P1_Completed = ?,
C2_S_Date = ? WHERE ERF_No = ?";
Your Sql Update statement syntax is wrong.Do put 'SET' for each column in the query, you only do it at the first column
change it to
String insert = "UPDATE PPN_WORKFLOW SET P1_F_Date = ?, P1_Completed = ?, C2_S_Date = ? WHERE ERF_No = ?";
stmt = conn.prepareStatement(insert);
stmt.setDate(1, date);
stmt.setInt(2, 1);
stmt.setDate(3, date);
stmt.setInt(4, erf_no);
stmt.executeUpdate();
Heres the syntax for you reference