nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar - spring

#Override
public int saved(Register r) {
String sql = "insert into tbl_register(fname,lname,email,phone,address,username,password,gender,use)values(?,?,?,?,?,?,?,?,?)";
return JdbcTemplate.update(sql,r.getFname(), r.getLname(), r.getEmail(), r.getPhone(), r.getAddress(), r.getUsername(), r.getPassword(), r.getGender(), r.getUse());
}

Related

SpringBoot+JDBCTemplate+Parent Key not found error

Unable to insert into child table in a single transaction using springboot and jdbctemplate.
Controller:
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public Response addUser(#RequestBody UserVo userVo) throws Exception
{
service.addUserRecord(userVo);
}
Service Layer:
#Autowired
private Dao dao;
#Transactional(readOnly = false)
public void addUserRecord(#RequestBody UserVo userVo) throws Exception
{
int parentSeqNo = dao.addUser();
int result = dao.addUserDetails(parentSeqNo, list);
}
DAOImple class:
#Autowired
private JdbcTemplate jdbcTemplate;
public int addUser()
{
try
{
String sql = "INSERT INTO user_table() VALUES (?,?,?,?,?) ";
jdbcTemplate.update(sql,....);
return seqNo;
}
catch(Exception e)
{
e.printStackTrace();
throw e;
}
}
public void addUserDetails(String seqNo, List<String> list){
String sql="insert into user_details_table values(?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
String img = list.get(i);
ps.setString(1, seqNo);
ps.setString(2, img);
}
public int getBatchSize() {
return list.size();
}
});
return;
}
Issue/Error:
ORA-02291: integrity constraint (FK3) violated - parent key not found; nested exception is java.sql.SQLIntegrityConstraintViolationException:
Database tables and constraints are looks good and tried to insert using sql editor, just working fine. While testing from postman tool, getting parent key not found exception. Greatly appreciated for any suggestions on this issue.

spring jdbc insert command

public void save(RegistrationBean registrationBean) throws SQLException {
String first_name = registrationBean.getFirst_name();
String last_name = registrationBean.getLast_name();
String email = registrationBean.getEmail();
String password = registrationBean.getPassword();
String phone = registrationBean.getPhone();
try {
int rows = jdbcTemplate.update("insert into users values(?,?,?,?,?)", first_name, last_name, email,password,phone);
System.out.println("inserted" + rows);
} catch (DataAccessException e) {
System.out.println(" not row inserted.reason : " + e);
}
}
this is my save method it gives sqlerror of org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [insert into users values(?,?,?,?,?)]; nested exception is java.sql.SQLException: Column count doesn't match value count at row 1.
Please anyone help solve the issue.

H2 "OTHER" data type throws Exception when storing String or Boolean

I understand that the OTHER data type can store any Serializable object. However when I try to store an instance of String or Boolean it fails with an exception.
Is this a misunderstanding on my part, or a bug in H2?
Here's repro code.
import org.h2.jdbc.JdbcSQLException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ScratchSpace {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
conn.createStatement().execute("drop table if exists test;");
conn.createStatement().execute("create table test (key VARCHAR, value OTHER)");
testInsert(conn, "key1", "foobar");
testInsert(conn, "key2", Boolean.TRUE);
testInsert(conn, "key3", new MyClass("foobar"));
conn.close();
}
private static void testInsert(Connection conn, String key, Serializable value) throws SQLException {
try (PreparedStatement statement = conn.prepareStatement("insert into test (key, value) values (?, ?)")) {
statement.setString(1, key);
statement.setObject(2, value);
statement.executeUpdate();
System.out.println("Insert of value={" + value + "} succeeded");
} catch (JdbcSQLException e) {
System.out.println("Insert of value={" + value + "} failed: " + e.getMessage());
e.printStackTrace();
}
}
public static class MyClass implements Serializable {
private final String s;
public MyClass(String s) {
this.s = s;
}
}
}
Here's a stack trace when I try to store String in the OTHER column:
org.h2.jdbc.JdbcSQLException: Hexadecimal string contains non-hex character: "foobar"; SQL statement:
insert into test (key, value) values (?, ?) -- (?1, ?2) [90004-188]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.util.StringUtils.convertHexToBytes(StringUtils.java:983)
at org.h2.value.Value.convertTo(Value.java:867)
at org.h2.table.Column.convert(Column.java:148)
at org.h2.command.dml.Insert.insertRows(Insert.java:143)
at org.h2.command.dml.Insert.update(Insert.java:114)
at org.h2.command.CommandContainer.update(CommandContainer.java:78)
at org.h2.command.Command.executeUpdate(Command.java:254)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:157)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:143)
at com.barbarysoftware.pokercopilot.ScratchSpace.testInsert(ScratchSpace.java:29)
at com.barbarysoftware.pokercopilot.ScratchSpace.main(ScratchSpace.java:19)

Invalid column type issue with spring JdbcTemplate

I am using spring JdbcTemplate.
public int countCallbackResponse(final int empId, final int noOfDay) {
int callbackCount = getJdbcTemplate().queryForInt(SurveyQuery.COUNT_CALLBACKS,
new PreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, empId);
ps.setInt(2, noOfDay);
}
}, Integer.class);
return callbackCount;
}
Error:
callback][org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [SELECT COUNT(sr.RESPONSEID) FROM EMPSUR s, EMPSURRES sr WHERE s.IEMPID = sr.IEMPID AND sr.IEMPID=? AND TRUNC(sr.TSCREATED) BETWEEN TRUNC(SYSDATE - (? + s.PRIORITY_DAYS)) AND TRUNC(SYSDATE) AND sr.SSTATUS IN ('SUS1','SUS1')]; SQL state [99999]; error code [17004]; Invalid column type; nested exception is java.sql.SQLException: Invalid column type]

Trivial create, insert with jdbctemplate

I'm trying to explore the basics of Spring's jdbctemplate. I'm having trouble with a simple example:
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
String url = "jdbc:h2:mem:test";
dataSource.setURL(url);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
jdbcTemplate.execute("create table something (id int primary key, name varchar(100))");
jdbcTemplate.execute("insert into something (id, name) values (1, 'Brian')");
}
Triggers this:
Caused by: org.h2.jdbc.JdbcSQLException: Table "SOMETHING" not found; SQL statement:
insert into something (id, name) values (1, 'Brian') [42102-177]
If I convert that code to use the raw JDBC api, it works fine:
public static void main(String[] args) throws Exception {
JdbcDataSource dataSource = new JdbcDataSource();
String url = "jdbc:h2:mem:test";
dataSource.setURL(url);
try (Connection dbConnection = dataSource.getConnection()) {
try (Statement statement = dbConnection.createStatement()) {
statement.execute("create table something (id int primary key, name varchar(100))");
statement.execute("insert into something (id, name) values (1, 'Brian')");
try (ResultSet rs = statement.executeQuery("select id, name from something")) {
while (rs.next()) {
System.out.println(String.format("got result. id=%d. name=%s", rs.getInt(1), rs.getString(2)));
}
}
}
}
}
If it matters, my Gradle dependencies:
compile 'org.springframework:spring-jdbc:4.0.6.RELEASE'
compile 'com.h2database:h2:1.4.177'
please try to use update method instead execute.

Resources