Why I get "java.sql.SQLException: Invalid column index "? - oracle

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 -------------------------------^

Related

Spring Boot and Hibernate Dynamic Id Generator for invoice Number

I am working on Spring boot Application with hibernate to create simple invoice.
I want to generate invoice number through hibernate in the following format
as below
YEAR/MONTH/Number(Will Increase)
The above sequence is dependent on invoice date.
Month and year values do change based on the current Date.
Once the year completed, let say after the completion of one financial
year the sequence again start from the beginning, like month/Year/number.
I have tried to Sequence Generator , table Generator . My Code snippet is as below :
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "year_gen")
#GenericGenerator(name = "year_gen", strategy = "com.example.generator.CustomGenerator")
#Column(name = "invoice_no")
private String invoiceno;
But I am not getting any idea that how to make it dependable on Invoice Date.
My Generator is below :
public class CustomGenerator implements IdentifierGenerator {
#Override
public Serializable generate(SharedSessionContractImplementor sessionImpl, Object data)
throws HibernateException {
Serializable result = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
String prefix = "";
DateTimeFormatter newPattern = DateTimeFormatter.ofPattern("yyyyMM");
LocalDate ldObj = LocalDate.now();
String yyyymm = newPattern.format(ldObj).toString();
prefix = "INV/"+yyyymm+"/";
connection = sessionImpl.connection();
statement = connection.createStatement();
try {
resultSet = statement.executeQuery("select max(id)+1 from invoice");
} catch(Exception ex) {
}
if(resultSet.next()) {
int nextValue = resultSet.getInt(1);
String suffix = String.format("%05d", nextValue + 1);
result = prefix.concat(suffix);
System.out.println("Custom generated Sequence value : "+result);
} else
{
int nextValue = 1;
String suffix = String.format("%05d", nextValue + 1);
result = prefix.concat(suffix);
}
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
}

ResultSet next() is returning only one row

I am having this method
public List<Course> getCourses() throws InvalidCourseDataException {
ArrayList<Course> allCoursesFromDB = new ArrayList<>();
Connection dbConnection = null;
String getFromTableSQL = "SELECT * FROM courses";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
resultSet = statement.executeQuery(getFromTableSQL);
while (resultSet.next()) {
String courseCategory = resultSet.getString("course_category");
String courseTitle = resultSet.getString("course_title");
int courseId = resultSet.getInt("course_id");
Date startDate = resultSet.getTimestamp("starting_date");
Date endDate = resultSet.getDate("ending_date");
String description = resultSet.getString("description");
int teacherId = resultSet.getInt("teacher_id");
Course course = new Course(courseCategory, courseTitle, startDate, endDate);
course.setCourseId(courseId);
course.setTeacherId(teacherId);
course.setDescription(description);
addParticipantsIdToCourse(course);
allCoursesFromDB.add(course);
}
The getDBConnection() method is
private static Connection getDBConnection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
My problem is that resultSet.next() is returning only the first row from DB. I'am sure that I have multiple rows. I saw JDBC ResultSet is giving only one row although there are many rows in table? that question but it really doesn't answer my :)
I am sorry for the question. I found my mistake. ResultSet next() method is working fine, but I've changed its value in my addParticipantsIdToCourse(course) method :)

Is it a good programming to pass Connection Object to a method?

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)
{
}

How do I display arrayList contents from resultset in Java JDBC?

So I am making a simple java project to play around with JDBC in glassfish and see how it works. The program just shows you a list of surveys and a list of questions for the survey you select. However i cant seem to display the list of questions for the survey I selected. I keep getting empty values. These are the methods I have created:
convert the resultset to object model data values
public JHAKSurvey findSurvey(long id) {
System.out.println("JDBC: FIND SURVEY");
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
JHAKSurvey survey = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.SURVEY WHERE ID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
survey = createSurveyFromResultSet(rs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
return survey;
}
private method to query the list of questions from the QUESTION table for a survey id
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ps.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}
private method to convert the find the resultset list to an question object and add it to the survey object
private void createQuestionFromResultSet(ResultSet rs, JHAKSurvey survey){
ArrayList<JHAKQuestion> qList = new ArrayList<JHAKQuestion>();
JHAKQuestion question = new JHAKQuestion();
JHAKSurvey ss = new JHAKSurvey();
//qList.add(survey.getQuestions());
try {
while (rs.next()) {
//question.setDescription(qList.toString());
question.setId(rs.getLong("ID"));
question.setDescription(rs.getString("DESCRIPTION"));
qList.add(question);
survey.setQuestions(qList);
}
System.out.println("createQuestionFromResultSet : JDBC : successful");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("createQuestionFromResultSet : JDBC : fail");
e.printStackTrace();
}
}
private method to convert a resultset to an survey object.
private JHAKSurvey createSurveyFromResultSet(ResultSet rs){
JHAKSurvey survey = new JHAKSurvey();
Boolean active = false;
String yes;
try {
yes = rs.getString("ACTIVE");
survey.setId(rs.getLong("ID"));
survey.setTitle(rs.getString("TITLE"));
if (yes.equals(Character.toString('Y'))) {
survey.setActive(true);
} else {
survey.setActive(false);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return survey;
}
What am I missing? I also seem to get error:
cannot convert from void to JHAKQuestion
When I try the method: createQuestionFromResultSet();
Thank You
Look at your method:
private void findQuestionsBySurvey(JHAKSurvey survey){
You want to get the questions of a survey, but the method returns void. Make it return a List<Question>. And in the body of the method, iterate through the resultset, transform each row into a question, add the question to a List<Question>, and return this list.
Or, if the goal of the method is to add questions to the survey passed as argument, then rename the method to
private void addQuestionsToSurvey(JHAKSurvey survey) {
and, inside the method body, call the method createQuestionFromResultSet (which should be named createQuestionsFromResultSetAndAddThemToSurvey), with the resultset and the survey as argument:
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ResultSet rs = ps.executeQuery(query);
createQuestionFromResultSet(survey);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}

JDBC connectivity issue

I'm using the NetBeans IDE(6.8). I have a DB class :
package garits;
import java.io.Serializable;
import java.sql.*;
import java.util.Properties;
public class DB implements Serializable{
private static final long serialVersionUID = 1L;
String dbURL = "jdbc:mysql:///team_project";
String user = "root";
String pwd = "arsenal";
String dbDriver = "com.mysql.jdbc.Driver";
private Connection dbCon;
private ResultSet r;
private Statement s;
public DB()
{}
public boolean connect() throws ClassNotFoundException,SQLException{
Class.forName(dbDriver);
Properties props = new Properties();
props.put(user, "root");
props.put(pwd, "arsenal");
props.put("charSet", "UTF-8");
props.put("lc_ctype", "UTF-8");
dbCon = DriverManager.getConnection(dbURL,props);
//dbCon = DriverManager.getConnection(dbURL,user,pwd);
return true;
}
public void close() throws SQLException{
dbCon.close();
if(r!=null)
r.close();
if(s!=null)
s.close();
}
public ResultSet execSQL(String sql) throws SQLException{
s = dbCon.createStatement();
r = s.executeQuery(sql);
return (r == null) ? null : r;
}
public int updateSQL(String sql) throws SQLException{
s = dbCon.createStatement();
int r = s.executeUpdate(sql);
return (r == 0) ? 0 : r;
}
public int updateSQL(String sql, String getID) throws SQLException{
s = dbCon.createStatement();
int autoIncValue = -1;
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
if (rs.next()) {
autoIncValue = rs.getInt(1);
}
return autoIncValue;
}
}
The jar file is im my library, but whenever I try to connect:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String result ="";
DB db = new DB();
try{
db.connect();
String query = "Select Role From User_Account Where Username=jTextField1.getText()AND Where Password=jTextField2.getText(); ";
ResultSet rs=db.execSQL(query);
while(rs.next())
{
result = rs.getString("Role");
}
if(result.equals(""))
{
JOptionPane.showMessageDialog(loginButton,"Access denied","Error Message",JOptionPane.ERROR_MESSAGE);
}
else if(result.equals("Administrator"))
{
MainPage_Admin admin = new MainPage_Admin();
}
}
catch(Exception e)
{
System.out.println("An error has occurred");
}
}
I get an error(the exception is caught)-the name of the database is "team_project" and password is "arsenal"-any ideas appreciated. I'm new to JDBC.
First step: use at least e.printStackTrace() in your catch-block to get some information from the exception. Otherwise you'll just be guessing.
MySQL database url connection property is wrong
jdbc:mysql://localhost:3306/<your database name>
instead of you are giving
jdbc:mysql:///team_project
modify and execute the program and better to handle the exception within the try/catch block instead of throws.

Resources