I am trying to get the values from the database using servlet and it retrieving fine inside the while loop only i can accessing the values retrieved from the database but i need to consolidatre all values into a single object. here is my code,
String moduleId = request.getParameter("moduleId").trim();
String temp[] = moduleId.split("/");
for(String s:temp){
String modId[]=s.split("/");
PreparedStatement ps = null;
Connection connection=DatabaseConnection.getConnection();
ps=connection.prepareStatement("select * from testcase_sahi where module_id=?");
ps.setString(1,modId[0]);
ResultSet rs=ps.executeQuery();
while(rs.next()){
System.out.println(".............TC ID...."+rs.getString("testcase_id"));
System.out.println(".............TC Name...."+rs.getString("testcase_name"));
testCase=rs.getString("testcase_name");
/*fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
System.out.println("****"+out.TC_OBJECT);
out.writeObject(testCase);
out.close();*/
}
you can simply store your data in a List...
String moduleId = request.getParameter("moduleId").trim();
String temp[] = moduleId.split("/");
for(String s:temp){
String modId[]=s.split("/");
PreparedStatement ps = null;
Connection connection=DatabaseConnection.getConnection();
ps=connection.prepareStatement("select * from testcase_sahi where module_id=?");
ps.setString(1,modId[0]);
ResultSet rs=ps.executeQuery();
List temporaryList = new ArrayList(); //HERE
while(rs.next()){
System.out.println(".............TC ID...."+rs.getString("testcase_id"));
System.out.println(".............TC Name...."+rs.getString("testcase_name"));
testCase=rs.getString("testcase_name");
temporaryList.add(testCase); //HERE
}
serializeData(temporaryList) //and HERE
}
Related
I have an sql database where I am attempting to load data from. RstImport Student is importing from the student table which contains firstName, middleName, lastName, phoneNumber and dob. RstImportModule is then importing from the moduleslist table which contains 6 modules and grades. The imported data from each is then used to create a new student object, with the modules and grades being added to an array in this object. The student object should then be added to the listOfStudents arraylist. I am receiving the error 'Operation not allowed after ResultSet closed'. When debugging eclipse is telling me there is an error occurring at the start of the second while loops. Why am I receiving this error?
public class LoadData {
public static ArrayList<Student> loadStudentData() throws ClassNotFoundException, SQLException {
Statement stm = null;
System.out.println("Connecting to Database");
System.out.println("**********************");
Connection myConn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/schoolstudentsystem", "root", "");
stm = myConn.createStatement();
String sqlImportStudent = "Select * From students";
String sqlImportModule = "Select * From moduleslist";
ResultSet rstImportStudent = stm.executeQuery(sqlImportStudent);
ResultSet rstImportModule = stm.executeQuery(sqlImportModule);
ModuleGrade[] moduleGradeArray = new ModuleGrade[6];
while (rstImportModule.next()) {
for(int i = 0; i < Student.modulesList.length; i++) {
ModuleGrade mg1 = new ModuleGrade(rstImportModule.getString("m1"), rstImportModule.getInt("mg1"));
ModuleGrade mg2 = new ModuleGrade(rstImportModule.getString("m2"), rstImportModule.getInt("mg2"));
ModuleGrade mg3 = new ModuleGrade(rstImportModule.getString("m3"), rstImportModule.getInt("mg3"));
ModuleGrade mg4 = new ModuleGrade(rstImportModule.getString("m4"), rstImportModule.getInt("mg4"));
ModuleGrade mg5 = new ModuleGrade(rstImportModule.getString("m5"), rstImportModule.getInt("mg5"));
ModuleGrade mg6 = new ModuleGrade(rstImportModule.getString("m6"), rstImportModule.getInt("mg6"));
moduleGradeArray[0] = mg1;
moduleGradeArray[1] = mg2;
moduleGradeArray[2] = mg3;
moduleGradeArray[3] = mg4;
moduleGradeArray[4] = mg5;
moduleGradeArray[5] = mg6;
}
while (rstImportStudent.next()) {
Student student = new Student(rstImportStudent.getString("firstName"), rstImportStudent.getString("middleName"),
rstImportStudent.getString("lastName"),
rstImportStudent.getString("email"), rstImportStudent.getString("phoneNumber"), rstImportStudent.getInt("dob"),
moduleGradeArray);
ClassGroup.listOfStudents.add(student);
}
}
rstImportStudent.close();
rstImportModule.close();
myConn.close();
return ClassGroup.listOfStudents;
}
}
If you call close on a statement it will automatically close the Con from whence it came as well.
Are you getting the error here?
rstImportStudent.close();
rstImportModule.close();
myConn.close();
What if there is an exception before you close? You should be using try with resources.
I have a Result set returned using a query:
String query = "select Bookname, SubjectName from books join Subjects on Subjects.SubjectID = Books.subjectID where classID = '1a'";
ResultSet temp = null;
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
temp = rs;
}
I was just wondering is it possible to turn the Resultset into two seperate arrays: eg BookName[] and BookSubject[] so I can show them in a list view later on? Relatively new to resultset and this concept in android
You should be able to easily iterate through the results on the result set, populating each array with the results as you interate.
Something like this:
...
ResultSet rs = st.executeQuery(query);
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> subjects = new ArrayList<String>();
while (rs.next()) {
names.add(rs.getString(1));
subjects.add(rs.getString(2));
}
// finally turn the array lists into arrays - if really needed
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
String[] subjectArr = new String[subjects.size()];
subjectArr = subjects.toArray(subjectArr);
Hope that helps!
as shown on the title, I have tried so hard to compare the user input with my database, it works with a true input, but when the input is not exist on my database I don't know what is the wrong on my below code, please help
private class da implements ActionListener{
public void actionPerformed(ActionEvent e){
Connection con = null;
Statement state = null;
Statement state2 = null;
ResultSet rs = null;
ResultSet rs2 = null;
String url = "jdbc:mysql://localhost:3306/المكتبة";
String unicode = "?useUnicode=yes&characterEncoding=UTF-8";
try{
con = DriverManager.getConnection(url+unicode,"root","");
state = con.createStatement();
state2 = con.createStatement();
rs = state.executeQuery("SELECT * FROM library WHERE author ='"+name.getText()+"'")
;
rs2=state2.executeQuery("SELECT * FROM library WHERE bookname ='"+title.getText()+"'");
while(rs.next()){
String authorname = rs.getString("author");
String bookname = rs.getString("bookname");
String categort = rs.getString("category");
int isbn = Integer.parseInt(rs.getString("ISBN"));
String data = "اسم المؤلف: "+authorname+"\n"+"اسم الكتاب: "+bookname+"\n"+"التصنيف: "+categort+"\n"+"ISBN: "+isbn;
if(name.getText().trim().equals(authorname))
txt.setText(data);
else
txt.setText("dosen't exist");
}
while(rs2.next()){
String authorname = rs.getString("author");
String bookname = rs.getString("bookname");
String categort = rs.getString("category");
int isbn = Integer.parseInt(rs2.getString("ISBN"));
String data2 = "اسم المؤلف: "+authorname+"\n"+"اسم الكتاب: "+bookname+"\n"+"التصنيف: "+categort+"\n"+"ISBN: "+isbn;
txt.setText(data2);
}
}
catch(Exception t){
}
}
}
}
First of all do not use string combining on sql queries, use PreparedStatement.
and try like this :
PreparedStatement upd = connect.prepareStatement("select * from library where author=?");
upd.setString(1,VariableToholdAuthor);
ResultSet rs = upd.executeQuery();
while(rs.next())
{
CompareVariable = rs.getString("name");
}
This will help you.
Here is the original code which has defined String-Array (25). It is working perfectly. But I don't need to define it as 25. Instead, I used arraylist. Please check my code.
Using String of array:
public String[] getemailAddr(String strAccountnbr) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
String[] emailAddress = new String[25];
int i=0;
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " ;
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress[i]=(rs.getString("EmailAddress"));
logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);
i=i+1;
}
return emailAddress;
}
Here, I need to change String-Array to Arraylist. I tried something like this,
public String[] getemailAddr(String strAccountnbr) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
//Newly tried //
ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
//Newly tried //
int i=0;
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " ;
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress[i]=(rs.getString("EmailAddress"));
logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);
i=i+1;
}
return emailAddress;
}
Email ids are get from database instead of example.com.
But I am getting
java.lang.ArrayIndexOutOfBoundsException: 0 error
in this line.
emailAddress[i]=(rs.getString("EmailAddress"));
Please help!
This is not how you use an ArrayList.
First, you need to write:
List<String> strArrEmailIds = new ArrayList<>();
So, program to the interface and use the Java 7 diamond operator.
Next, remove the index i. You don't need this.
Finally, just do:
emailAddress.add(rs.getString("EmailAddress"));
To convert it back to an String[] you can then do:
String[] arr = emailAddress.toArray(new String[emailAddress.size()]);
Here is my suggestion for you final code:
public String[] getemailAddr(String strAccountnbr) throws Exception {
final List<String> emailAddress = new ArrayList<>();
final String strQuery2 = "SELECT c.EmailAddress AS EmailAddress"
+ " FROM customeremailid c "
+ "WHERE c.AccountNbr = ? ";
try (final PreparedStatement ps = getDBConn().prepareStatement(strQuery2)) {
ps.setString(1, strAccountnbr);
try (final ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
emailAddress.add(rs.getString("EmailAddress"));
}
}
}
return emailAddress.toArray(new String[emailAddress.size()]);
}
I have removed your pointless assignments to null. I have added try-with-resources blocks to close your external resources, you code was one massive memory leak.
If you have a ArrayList, then you dont need a array again, indeed a ArrayList is backed by Array itself and its dynamic in size.
List<String> emailAddress= new ArrayList<String>(); // dynamic array
...
while(rs.next()){
emailAddress.add((rs.getString("EmailAddress"));
...
}
return emailAddress.toArray(new String[emailAddress.size()]); // creating array of String type
And ArrayList#toArray converts List to Array which has done at last in the code.
declare it as
ArrayList<String> emailAddress= new ArrayList<String>();
...
emailAddress.add((rs.getString("EmailAddress"));
convert it to String[]:
return emailAddress.toArray(new String[emailAddress.size()]);
You use ArrayList here wrongly in your code. When you define
ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
strArrEmailIds by default has a size of 0, so the generated emailAddress array also gets a length of 0. Later in the while loop, you are trying to assign the value to the emailAddress[0], it will throw ArrayIndexOutOfBoundsException.
Instead, the correct way is :
ArrayList<String> strArrEmailIds = new ArrayList<String>();
//....
while(rs.next()){
//....
strArrEmailIds.add(rs.getString("EmailAddress"));
}
//....
String[] emailAddress = strArrEmailIds.toArray(new String[strArrEmailIds.size()]);
java.lang.ArrayIndexOutOfBoundsException: 0 if your result set goes beyond 25 itteration.
How to convert array to ArrayList ?
Arrays.asList(myArray)
in your case you can have a list and in the resulset itteration you can add them to the list like
List<String> emails = new ArrayList<String>();
while(...){
emails.add(rs.getString("EmailAddress"));
}
I'm wondering how to refresh database after inserting a new row without reopening whole application. I want to be able to see new data in next steps of my application. I can't find any solution, so i would be happy if you post the example. Of course if it is possible.
Here is my connection method
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:FlowValves";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
}catch(Exception ex){
ex.printStackTrace();
}
Here is one of my inserting methods.
String sql = "select * from Typy";
try{
ResultSet result;
result = st.executeQuery(sql);
result.moveToInsertRow();
String stringNazwa = (String)nazwaZaworuField.getText();
result.updateString("Typ", stringNazwa);
String stringDN = (String)dnZaworuField.getText();
result.updateString("DN", stringDN);
String stringPN = (String)pnZaworuField.getText();
result.updateString("PN", stringPN);
String stringIndeks = (String)indeksField.getText();
result.updateString("Indeks", stringIndeks);
result.insertRow();
result.close();
JOptionPane.showMessageDialog(null, "Wprowadzono dane", "Komunikat", JOptionPane.INFORMATION_MESSAGE);
}catch(Exception ex){
ex.printStackTrace();
}
Your code for inserting looks correct (although I would use an insert statement instead of using moveToInsertRow() )
You should be able to requery the database and put the new data on the screen:
String sql = "select * from Typy";
ResultSet result;
result = st.executeQuery(sql);
while( result.next() ){
sting indeks = result.getString( "indeks" );
// etc.
// do something with the new data
}