Trying to update multiple column values in a table.
What I am missing, a little help!
The dao method is like...
The dao class Plan has all the fields populated with appropriate data.
public void updatePlan(Plan plan) {
SqlParameterSource mapSqlParameterSource = new MapSqlParameterSource().addValue("id", plan.getId())
.addValue("plan_name", plan.getPlan())
.addValue("price_category", plan.getPrice_category())
.addValue("updated_by", subscriptionPlan.getId());
String UPDATE_PLAN = "UPDATE plan_table SET(plan_name= :plan_name, price_category= :price_category, updated_by= :id) where id=:id)";
SqlParameterSource parameterSource = new BeanPropertySqlParameterSource(subscriptionPlan);
namedParameterJdbcTemplate.update(UPDATE_PLAN, mapSqlParameterSource);
}
The error is...(MySQL database - 5.6.43, Workbench - 6.3.9)
org.springframework.jdbc.BadSqlGrammarException:
PreparedStatementCallback; bad SQL grammar [update webstat_plan set (plan_name= ?, price_category= ?, updated_by= ?) where id=?)]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax....
Issue is with your SQL Query.
Parenthesis is not required while updating the table.
Update your query with
UPDATE plan_table SET plan_name= :plan_name, price_category= :price_category, updated_by= :id where id=:id
Related
I want to use jdbcTemplate to create table based on another table under condition. I have postgres database. When I execute this and pass parameter:
String SQL = "create table test as (select * from users where countryId =?)";
jdbcTemplate.update(SQL, new Object[] {3})
I receive table test with all columns from users table but with no rows.
However, when I execute this:
String SQL = "create table test as (select * from users where countryId =3)";
jdbcTemplate.update(SQL)
I receive test table with rows where countryId = 3, so that is what I was expecting to receive in the first solution.
Your passing of the bind variable is not correct, but it does not play any role.
You simple can not use a bind variable in a data definition statement as you immediately see in the triggered error
Caught: org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL
[create table test as (select * from users where countryId =?)];
SQL state [72000]; error code [1027];
ORA-01027: bind variables not allowed for data definition operations
So you have two options, either concatenate the statement (which is not recommended due to the danger of SQL injection)
or split the statement in two parts:
// create empty table
sql = "create table test as (select * from users where 1 = 0)";
jdbcTemplate.update(sql)
// insert data
sql = "insert into test(countryId, name) select countryId, name from users where countryId =?";
updCnt = jdbcTemplate.update(sql, new SqlParameterValue(Types.INTEGER,3));
Note that in the insert statement you can see the correct way of passing an interger value of 3 as a bind variable.
You can follow below approach as well:-
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)");
List<Object[]> employeeIds = new ArrayList<>();
for (Integer id : ids) {
employeeIds.add(new Object[] { id });
}
jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds);
Here you may query with 2 operations to avoid SQL injection.
You are using method update from jdbcTemplate in a wrong way.
Try with this:
String SQL = "create table test as (select * from users where countryId = ?)";
jdbcTemplate.update(SQL, 3);
I have below query o delete records from SYBASE database. I am using Spring NamedParameterJDBCTemplete
String query = "Delete FROM PRODUCTS WHERE ID IN (:ids)"
Have written below function to delete records
void deleteRecords(List<ID> ids){
SqlParameterSource parameters = new MapSqlParameterSource("ids", ids);
try{
namedParameterJDBCTemplate.update(query, parameters)
}
catch(Exception e){
}
}
I keep getting error below
org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [Delete from PRODUCTS WHERE ID IN ()]; nested exception is com.sybase.jdbc4.jdbc.SybSQLException: Incorrect syntax near ')'
I'm trying to make an update query in HQL, but in doesn't work, I'm using MySQL5Dialect. In Patient class all variables are annotated just like column's names in database. Here is a code:
Controller:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("clinic");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
Patient patient = new Patient();
patient.setFirstName(infonameField.getText());
patient.setLastName(infolastNameField.getText());
patient.setGender(infogenderField.getText());
patient.setAge(infoageField.getText());
patient.setPhonenumber(infophonenumberField.getText());
patient.setAddress(infoadressField.getText());
patient.setDisease(infodiseaseField.getText());
patient.setCondition(infoconditionField.getText());
patient.setRoomtype(infoRoomType.getText());
patient.setRoomNumber(infoRoomNumber.getText());
patient.setDateregistration(infodataField.getText());
patient.setIdpatient(infoPIDField.getText());
Query query = entityManager.createQuery("UPDATE Patient set name = :name, lastname= :lastname,"
+ "gender= :gender, age= :age, phonenumber= :phonenumber, address= :address, disease= :disease,"
+ "condition= :condition, roomtype= :roomtype, roomnumber= :roomnumber, "
+ "dateregistration= :dateregistration WHERE idpatient= :idpatient");
query.setParameter("name", patient.getFirstName());
query.setParameter("lastname", patient.getLastName());
query.setParameter("gender", patient.getGender());
query.setParameter("age", patient.getAge());
query.setParameter("phonenumber", patient.getPhonenumber());
query.setParameter("address", patient.getAddress());
query.setParameter("disease", patient.getDisease());
query.setParameter("condition", patient.getCondition());
query.setParameter("roomtype", patient.getRoomtype());
query.setParameter("roomnumber", patient.getRoomNumber());
query.setParameter("dateregistration", patient.getDateregistration());
query.setParameter("idpatient", patient.getIdpatient());
query.executeUpdate();
entityManager.getTransaction().commit();
Error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition='ewqewqeq', roomtype='standard', roomnumber='101', dateregistration='2' at line 1
The word condition is a keyword in MySQL, probably that's the reason of your error. Try modifying it or replace it by another name.
EDIT
After reading this MySQL forum post, you can use it as long as you escape it, as mentioned here.
I'm struggling with following exception:
org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [update EVALUATION_SHEET set STATUS=?, LAST_EDITED=? where id=?]; SQL state [99999]; error code [17004]; Invalid column type; nested exception is java.sql.SQLException: Invalid column type
Which is thrown here:
jdbcTemplate.update("update E_SHEET set STATUS=?, LAST_EDITED=? where id=?",
new Object[]{eSheet.getStatus().ordinal(), eSheet.getLastEditDate(), eSheet.getId()},
new Object[]{OracleTypes.NUMBER, OracleTypes.TIMESTAMP, OracleTypes.NUMBER});
The database table is created as follows:
create table E_SHEET (
ID number not null unique,
ID_POSITION number not null,
STATUS number default 0 not null,
ID_EXAMINER number not null,
LAST_EDITED timestamp not null);
I have no idea what is causing the problem. This method:
eSheet.getLastEditDate()
returns java.util.Date object. I am using Spring JDBC template with Spring Boot and Oracle DB 12c as a datasource.
after the spring documentation http://docs.spring.io/spring/docs/current/spring-framework-reference/html/jdbc.html, an update would work like this:
jdbcTemplate.update("update t_actor set last_name = ? where id = ?", "Banjo", 5276L);
or like this
jdbcTemplate.update("update orders set shipping_charge = shipping_charge * ? / 100 where id = ?", pct, orderId);
But you are passing arrays of Objects as parameters to the method.
Why not just this?
jdbcTemplate.update("update E_SHEET set STATUS=?, LAST_EDITED=? where id=?", eSheet.getStatus().ordinal(), eSheet.getLastEditDate(), eSheet.getId());
Thanks for your time
I am getting an error as my project is having 2 modules add driver and add truck for which i am executing the sql query for both but when i execute the query for addDriver module the database exception is throwing stating
org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL [INSERT INTO truck(TRegnNo,VendorName,PurchaseDate,Price,RepairDate,InvoiceNo,RepairCost) VALUES(?,?,?,?,?,?,?)]; Column 'TRegnNo' cannot be null; nested exception is com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Column 'TRegnNo' cannot be null
org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:101)
driver insert sql statement public void insertData(Driver driver)
{
String sql = "INSERT INTO driver" + "(DLNo,DName,Age,Experience) VALUES (?,?,?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql, new Object[] {driver.getLicenseNumber(),driver.getDriverName(),driver.getAge(),driver.getExperience()});
} Truck Insert code public void insertData(Truck truck)
{
String sql = "INSERT INTO truck" + "(TRegnNo,VendorName,PurchaseDate,Price,RepairDate,InvoiceNo,RepairCost) VALUES(?,?,?,?,?,?,?)";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.update(sql , new Object[] {truck.getTregNo(),truck.getVendorName(),truck.getPurchaseDate(),truck.getPrice(),truck.getRepairDate(),truck.getInvoiceNo(),truck.getRepairCost()});
}
Column TRegnNo can not be null. You have to assign a (unique) value to this row.
Check out with this :
StackTrace contains Column 'TRegnNo' cannot be null pointing to constraints in Truck table, like primary key or foreign key etc..