I have different values in different classes. I need to insert them in the same table. For example, by trying the example in this tutorial here: http://www.vogella.com/articles/MySQLJava/article.html
If I have such code (assuming the DB connection successfully done in another class):
// PreparedStatements can use variables and are more efficient
preparedStatement = connect.prepareStatement("insert into FEEDBACK.COMMENTS
values (default, ?, ?, ?, ? , ?, ?)");
// "myuser, webpage, datum, summery, COMMENTS from FEEDBACK.COMMENTS");
// Parameters start with 1
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "TestEmail");
preparedStatement.setString(3, "TestWebpage");
preparedStatement.setDate(4, new java.sql.Date(2009, 12, 11));
preparedStatement.setString(5, "TestSummary");
preparedStatement.setString(6, "TestComment");
preparedStatement.executeUpdate();
Assume that in one class I want to insert value 1, in the second class, I want to insert value 2, etc. By the end of my program, in the main function, I want to execute the update. Note that I wrote the:
preparedStatement = connect.prepareStatement("insert into FEEDBACK.COMMENTS
values (default, ?, ?, ?, ? , ?, ?)");
is in the main function. I have tried to define preparedStatement as public variable in the class that contains the main function, and if, for example, I need to insert value 2 in another class, I type:
preparedStatement.setString(2, "TestEmail");
but this results in error in the main function says: No value specified for parameter 2. So, how can I insert values from different classes in one table ??
Since you are using “preparedStatement” variable in main, I assume it must be a public static variable. And since you expect other classes to execute methods on this variable, I am assuming you are doing it in static initializers of these classes or in static constructors. The problem is these classes are not loaded (and hence their static initializers are not run) unless you reference these classes from main (calling a static method on the class or creating a new instance). I think you are not doing so. That is why none of the static initializers of these classes are run and you don’t have an preparedStatement that is ready to be executed.