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..
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 ')'
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
I have couple of questions:
1) First basic question how can i execute multiple statements
(Create temp table and Select from temp table) using same jdbc connection in spring jdbctemplate?
2) I am creating temp table using below sql statement. JDBCTemplate execute(String sql) method doesn't accept any parameters then how to run it using jdbc template
Select column1, column2, column3... into #t
from Table where column1 >= ? and column1 < ?
In JUtil I use single connection wrapper:
dataSource = new org.springframework.jdbc.datasource.SingleConnectionDataSource(dataSource.getConnection(), true);
#Test
public void testTemporaryTable() {
JdbcTemplate dao = new JdbcTemplate(dataSource);
dao.update("create local temporary table test_table as select 'text' id");
Assert.assertEquals("text", dao.queryForObject("select id from test_table ", String.class));
}
how to use sequence in namedparameterJDBCTemplate for insertion into two tables ?
Database- orcale
springjdbcnamedparametertemplate .
my Dao is looking like this
#Override
public void insert(Message message) {
String SQL = "INSERT into mssg (mssg_id, mssg_text, mssg_channel)"
+ " values (mssg_sequence.nextval,:mssg_text,:mssg_channel)";
String SQLMessage_app = "INSERT into message_app(mssg_app_type,mssg_id)"
+ "values(:mssg_app_type,mssg_sequence.currval)";
namedParameterJdbcTemplate.update(SQL,
new BeanPropertySqlParameterSource(message));
namedParameterJdbcTemplate.update(SQLMessage_app,
new BeanPropertySqlParameterSource(message));
}
oracle tables are these
This is the first table
create table mssg (
mssg_id number(10) NOT NULL,
mssg_text varchar2(25)NOT NULL,
mssg_channel varchar(25)NOT NULL,
constraint pk_mssg_id PRIMARY KEY(mssg_id)
);
Create sequence mssg_sequence
start with 1
increment by 1
minvalue 1
maxvalue 100000;
This is the second table
CREATE TABLE MESSAGE_APP(
mssg_app_type VARCHAR2(25),
mssg_id NUMBER(10),
CONSTRAINT fk_mssg
FOREIGN KEY(mssg_id)
REFERENCES mssg(mssg_id)
ON DELETE CASCADE);
COMMIT;
iam getting this error :
org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL [INSERT
into
message_app(mssg_app_type,mssg_id)values(?,mssg_sequence.currval)];
SQL state [72000]; error code [8002]; ORA-08002: sequence
MSSG_SEQUENCE.CURRVAL is not yet defined in this session ; nested
exception is java.sql.SQLException: ORA-08002: sequence
MSSG_SEQUENCE.CURRVAL is not yet defined in this session
can anybody help me to insert data into two tables by using sequence???
Thanks in advance :)