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.
Related
Spring transactions in multiple instance application is failing regularly. Unable to reproduce. Failing with PK constraint(jobname+key)
Note: I have modified the query part to look-alike
#Override
#Transactional(propagation = Propagation.REQUIRES_NEW, isolation = Isolation.READ_COMMITTED)
public boolean insertLockIfDoesNotExist(String jobName, String key) {
try {
int affectedRowsCount = entityManager.createNativeQuery(
"insert into LOCK_SCH (JOB_NAME, KEY) select ?, ? where not exists (select 1 from LOCK_SCH where JOB_NAME=? and EXECUTION_KEY=?) ")
.setParameter("jobName", jobName)
.setParameter("key", key)
.setFlushMode(FlushModeType.AUTO)
.executeUpdate();
return affectedRowsCount > 0;
} catch (Exception e) {
throw e;
}
}
I try to pass number into PrepareStmt, but get this error. I can't understant my problem.
Query:
private static final String SQL_FIND_ALL_CALENDARS = "SELECT * FROM calendar WHERE idCall > '?';";
Function:
private List<Calendar> findAll(Connection con) throws SQLException {
List<Calendar> calendar = new ArrayList<Calendar>();
PreparedStatement prsmt = null;
ResultSet rs = null;
try {
prsmt = con.prepareStatement(SQL_FIND_ALL_CALENDARS);
prsmt.setInt(1, TestOracleJDBC.idCall);
rs = prsmt.executeQuery();
while (rs.next()) {
Calendar calendar2 = extractCalendar(rs);
calendar.add(calendar2);
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
rs.close();
prsmt.close();
}
return calendar;
}
In other class my parameter:
public static int idCall = 1;
Single quotes (') denote string literals in SQL. When using bind variables you shouldn't surround the ? with quotes - that would change it into a string literal with a question mark, not a placeholder for binding values.
Just remove it and you should be OK:
private static final String SQL_FIND_ALL_CALENDARS =
"SELECT * FROM calendar WHERE idCall > ?";
// Here -------------------------------^
I am trying to get Table names for hive using DatabaseMetaData in a similar way like RDBMS.
Sample code:
try (Connection con = getJdbcConnection(connectionUri, driverName, username, password);) {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getTables(null, null, tableName, null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
} catch (SQLException e) {
}
private static void registerDriver(String driverName) {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
LOG.error("No class found for " + driverName + ". Details: " + e);
}
}
private static Connection getJdbcConnection(String connectionUri, String driverName, String username,
String password) throws SQLException{
registerDriver(driverName);
return DriverManager.getConnection(connectionUri, username,password);
}
There is no table in a particular database. Using different different table names, I am getting different output.
For example:
I put table name emp, there are 3 records with name emp
I put table name employee, there are 5 records with name employee
I put table name emp12, it is returning no records (which is expected)
Am I doing something wrong?
Shouldn't I use DatabaseMetaData for checking table existence?
I need to pass schema name in getTables method
Signature:
ResultSet getTables(String catalog,
String schemaPattern,
String tableNamePattern,
String[] types)
throws SQLException
I passed following agruments:
catalog = null;
schemaPattern = Hive schema Name
tableNamePattern = Hive Table Name
types = new String[] { "TABLE" }
Sample code:
try (Connection con = getJdbcConnection(connectionUri, driverName, username, password);) {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getTables(null, schemaName, tableName, new String[] { "TABLE" });
while (rs.next()) {
String tName = rs.getString("TABLE_NAME");
if (tName != null && tName.equals(tableName)) {
LOG.info("Table [" + tableName + "] is present in the Database.");
return true;
}
}
rs.close();
LOG.info("Table [" + tableName + "] is not present in the Database.");
return false;
} catch (SQLException e) {
LOG.error("Not able to get Table Metadata . Caused By: " + e);
}
I am doing a Insert Operation , i have a condition if company is 0 , then i need to perform an additional insert in another table ??
This is my code
public static String insertIntoDepotTable(DepotJSONBean depotbean) throws SQLException
{
Connection dbConnection = null;
PreparedStatement depotjsoninsertPst = null ;
try
{
dbConnection = DBConnectionOrientDepot.getDBConnection();
dbConnection.setAutoCommit(false);
String companyId = depotbean.getCompanyId();
if(companyId.equals("0"))
{
saveInCompany(depotbean , dbConnection);
}
String Insertsql = "INSERT INTO tbl_depot values (depotID,depoBelongsToID,stateID,districtID,talukMandalID,depotName,companyID,contactName,phone1,phone2,address,latitude,longititude,accuracy,town,noOfPeopleOperating,depotSize,storageCapacity,cAndFNames,depotPic1,depotPic2,comments,active,createdOn,modifiedOn) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
depotjsoninsertPst = dbConnection.prepareStatement(Insertsql);
}
catch(Exception e)
{
}
} // end of method
public String saveInCompany(DepotJSONBean djsonbean , Connection conn)
{
}
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]