I code this method to fetch result from SQLite table in java.
public String[][] select(String query, String table) throws ClassNotFoundException, SQLException
{
Connection con;
Statement st;
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:"+table);
con.setAutoCommit(false);
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
String[][] result = new String[100][4];
int j = 0;
while ( rs.next() ) {
String name = rs.getString("fullname");
String username = rs.getString("username");
String password = rs.getString("password");
String email = rs.getString("email");
result[j][0] = name; // line number 63
result[j][1] = username;
result[j][2] = password;
result[j][3] = email;
j++;
}
rs.close();
st.close();
con.close();
return result;
}
From my main method i instantiated this method:
try{
String[][] data = db.select("SELECT * FROM user", "fliplist.db"); // line number 37
System.out.println(data);
} catch (ClassNotFoundException | SQLException e){
System.out.println(e.getMessage());
}
This gives me this error:
run:
Exception in thread "main" java.lang.NullPointerException
at FlipList.Database.select(Database.java:63)
at FlipList.FlipList.main(FlipList.java:37)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)
How it should be in order to fetch the result?
Update
I have initialized the second dimension of the array, and now it showing this error(most likely garbez value):
run:
[[Ljava.lang.String;#2077d4de
BUILD SUCCESSFUL (total time: 2 seconds)
How i can return an array?
(Thanks to #lea for this; if they've posted one please let me know)
You need to initialize the inner arrays, too. In your while loop, put something like this at the top, and it should work.
data[j] = new String[4];
For your new error, you want to iterate through the array instead of just printing it. For example:
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[0].length; j++) {
System.out.print(data[i][j] + "\t\t");
}
System.out.println();
}
There are also a couple of other tips that I'd like to give you:
Move the j++ into the while loop, just before the closing bracket. That way it increments with every loop instead of just once, after every loop. Fixed!
You might want to use an ArrayList<String[]> instead of String[][] if you won't always have exactly a hundred items. That way, you can go over 100 if you need, and if you use less, it will save memory. To do that, you'll want to do something like this for your while loop:
while ( rs.next() ) {
String[] nextRow = new String[4];
String name = rs.getString("fullname");
String username = rs.getString("username");
String password = rs.getString("password");
String email = rs.getString("email");
nextRow[0] = name; // line number 63
nextRow[1] = username;
nextRow[2] = password;
nextRow[3] = email;
result.add(nextRow);
}
You'll also want to change the declaration of data to ArrayList<String[]> result = new ArrayList<String[]>() instead of String[][] result = ....
i redefined the ArrayList as the list of Strings rather than Arrays.
public void tester()
{
ArrayList result = new ArrayList();
try
{
Connection connect = DriverManager.getConnection(host, username, password);
String sql="select * from FRIENDS";
Statement stmt=connect.createStatement();
ResultSet rs=stmt.executeQuery(sql);
String[] nextRow = new String[4];
while ( rs.next() ) {
String firstname = rs.getString("FIRSTNAME");
String lastusername = rs.getString("LASTNAME");
String nickname = rs.getString("NICKNAME");
String friendsince = rs.getString("FRIENDSINCE");
String email = rs.getString("EMAIL");
System.out.print("Firstname :- "+firstname+" lastname :- "+lastusername+" nickname :- "+nickname+" friendsince :- "+friendsince+" Email :- "+email);
nextRow[0] = firstname;
nextRow[1] = lastusername;
nextRow[2] = nickname;
nextRow[3] = email;
System.out.println("The values in array are :- "+nextRow);
int i=0;
for(i=0;i<nextRow.length;i++)
{
String add1=nextRow[i];
result.add(add1);
}
}
}
Hope , this helps.
Something very basic . Please execute the query on the DB and see what it returns(Sometimes the query might not be correct e.g the table name can be 'users' instead of 'user', just a guess) :-
SELECT * FROM user
If above is fine , then can you please try extracting the rows using 'columnIndex' instead of the 'columnName'. e.g.
String name = rs.getString(1);
String username = rs.getString(2);
String password = rs.getString(3);
String email = rs.getString(4);
Here i am assuming that the name , username , password and email belong to 1st , 2nd ,3rd and 4th column respectively.
Related
I want to display values from database in many lines using jLabel. I tried using the html trick but I don't know how to apply it here in my code. I just get errors. Maybe I'm doing it the wrong way. Haha.
try{
//display doctor's name by selected classification
String url = "jdbc:mysql://localhost/sched";
Connection conn = DriverManager.getConnection(url,"root","");
Statement stmt = conn.createStatement();
String classification = comboClass.getSelectedItem().toString();
String sqlSelect= "select * from doctorsched where class = '"+classification+"'";
ResultSet rs = stmt.executeQuery(sqlSelect);
String finalText ="";
while(rs.next()){
String docsName= rs.getString("docName");
String room = rs.getString("room");
String days = rs.getString("day");
String from = rs.getString("timefrom");
String to = rs.getString("timeto");
finalText += docsName+" (room "+room+", "+days+", "+from+"-"+to+") \\n";
// i want to display values from database in many lines but using jLabel
}
jLabel10.setText(finalText);
} catch (Exception ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
Something like this should be my output
doc riza (room 104, Every Thursday, 10:30AM-10:00AM)
doc j (room 101, null, 10:30AM-11:30AM)
doc lea (room 102, Every Saturday, 10:30AM-4:30PM)
frida (room 101, null, 8:00AM-9:30AM)
Please help me out :(
The '\n' works in jTextArea but not in jLabel. I also tried '\n' in label, but doesn't work, too.
Okay so I tried this one
finalText += "<html>"+docsName+" (room "+room+", "+days+", "+from+"-"+to+")<br></html>";
But this code only display one line. The first row in my database. I need to display all of the rows.
Now, this next code shows it all, but the next line still doesn't work.
while(rs.next()){
String docsName= rs.getString("docName");
String room = rs.getString("room");
String days = rs.getString("day");
String from = rs.getString("timefrom");
String to = rs.getString("timeto");
finalText += docsName+" (room "+room+", "+days+", "+from+"-"+to+")\n";
}
jLabel10.setText("<html>"+finalText+"<br></html>");
}
Whyyy
use a code like this
String finalText = "";
for (int i = 0; i < 10; i++) {
finalText += "line:" + i;
finalText += "<br>";
}
label.setText("<html>" + finalText + "</html>");
try{
//display doctor's name by selected classification
String url = "jdbc:mysql://localhost/sched";
Connection conn = DriverManager.getConnection(url,"root","");
Statement stmt = conn.createStatement();
String classification = comboClass.getSelectedItem().toString();
String sqlSelect= "select * from doctorsched where class = '"+classification+"'";
ResultSet rs = stmt.executeQuery(sqlSelect);
String finalText ="";
while(rs.next()){
String docsName= rs.getString("docName");
String room = rs.getString("room");
String days = rs.getString("day");
String from = rs.getString("timefrom");
String to = rs.getString("timeto");
finalText += (docsName+" (room "+room+", "+days+", "+from+"-"+to+")\n") ;
finalText += "<br>";
}
jLabel10.setText("<html>" + finalText + "</html>");
} catch (Exception ex) {
Logger.getLogger(home.class.getName()).log(Level.SEVERE, null, ex);
}
I want this function to display the highest value and the index in the array.If the index is the highest, it will retrieve all the value in sql. But when I run this program, it displays a lot of values...How to solve it?
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0];
System.out.println(highest); // display value in aa[0]
for(int i=1;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
System.out.println(highest); //print the highest value only
System.out.println(i);
String sql ="Select * from placeseen where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, i+1);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
else if(highest==aa[0])
{
String sql ="Select * from placeseen where ID =1";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
}
Use MAX
Please change your approach, and use the SQL MAX function. Something like,
String sql = "SELECT * FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
You could then use something like
int id = rs.getInt("id");
float budget = rs.getFloat("budget");
And I would recommend limiting the columns (if you only want the two) like
String sql = "SELECT id, budget FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
Why not use a for (int i = 0; i < array.lenght; i++)?
Store array[i] in a variable, and the actual int found in that index in another variable. Then, when you loop through it more: if (array[i] > biggestInt), store the new index number and new biggest integer in their appropriate variables.
Ok so this is my code
public static ArrayList getMaterialerFraOrdreNr(String s_date, String e_date) throws SQLException, InterruptedException {
int tal = 0;
ArrayList nameOfColumns = getNameOfColumns(); // name of columns
ArrayList orderNumber = getOrdre_Nr_FromDB(s_date, e_date); // order number
//første loop kører gennem number of columns
//anden loop kører gennem name of column
ResultSet rs = null;
Connection con = null;
try {
Class.forName(DB.driver);
con = DriverManager.getConnection(DB.URL, DB.ID, DB.PW);
for (int i = 1; i < orderNumber.size(); i++) {
for (int j = 1; j < nameOfColumns.size(); j++) {
String nameOfColum = (String) nameOfColumns.get(i);
int orderNr = (Integer) orderNumber.get(j);
System.out.println("orderNr " + orderNr);
//SELECT v1001 FROM ORDRE_spec WHERE ordre_nr = 1;
String query = "SELECT ? AS ans FROM ordre_spec WHERE ordre_nr = ?";
PreparedStatement prest = con.prepareStatement(query);
prest.setString(1, nameOfColum);
prest.setInt(2, orderNr);
System.out.println("orderNr " + orderNr);
System.out.println("nameOfColum = " + nameOfColum);
rs = prest.executeQuery();
if(rs.next()){
tal = rs.getInt("ans");
MaterialeNum.add(tal);
System.out.println("materiale num = " + MaterialeNum);
}
}
}
} catch (ClassNotFoundException | SQLException ee) {
System.out.println("fail og der er så her");
System.err.println(ee);
} finally {
con.close();
}
System.out.println(kundeNum.toString());
return kundeNum;
}
public static void main(String[] args) throws SQLException, InterruptedException {
NewClass.getMaterialerFraOrdreNr("1990-10-10", "2020-10-10");
}
And my problem is that I'm getting a java.sql.SQLException: Fail to convert to internal representation
I really cant see what the error should be.. plz help if you can see the error :)
String query = "SELECT ? AS ans FROM ordre_spec WHERE ordre_nr = ?";
You cannot parameterize column names. You can only parameterize column values.
Basically you need to do:
String query = "SELECT " + nameOfColum + " AS ans FROM ordre_spec WHERE ordre_nr = ?";
Keep in mind that this is prone to SQL injection if nameOfColum is controllable by enduser. If this is indeed the case, you may want to perform string matching on e.g. \w+ before continuing.
This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 8 years ago.
Hello I'm trying to make an error when there is no matched student...
and it will display like this
No matching records found and I want the column name still the same but still not figuring it out... can some one tell me if this is right??
Heres my function for that... and I add comment there where I put the error... but i don't know how to get the columnname
public void SearchTableStudent() {
String tempSearchValue = searchStudent.getText().trim();
boolean empty = true;
sql = "SELECT student_id as 'Student ID',"
+ "concat(lastname, ' , ', firstname, ' ', middlename) as 'Name'"
+ "FROM user "
+ "WHERE CAST(student_id as CHAR) LIKE '%" + tempSearchValue + "%'";
try {
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()) {
table.setModel(DbUtils.resultSetToTableModel(rs));
empty = false;
}
if(empty) {
String error = "";
table.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"No matching records found",null}
},
new String [] {
/** I WANT TO PUT THE SAME COLUMN NAME ON MY DATABASE SELECTED BUT DON't Know
WHAT FUNCTION TO DO*/
}
));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
I try like this but still gave me NULL!!!
this code is below of empty = false;
for(int i=0; i<table.getColumnCount(); i++) {
test[i] = table.getColumnName(i);
}
ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];
for (int i = 1; i <= count; i++)
{
columnName[i-1] = metaData.getColumnLabel(i);
System.out.println(columnName[i-1]);
}
Try this.
ResultSetMetaData meta = resultset.getMetaData();
Integer columncount = meta.getColumnCount();
int count = 1 ; // start counting from 1 always
String[] columnNames = new String[columncount];
while(count<=columncount){
columnNames [count-1] = meta.getColumnLabel(count);
count++;
}
Since here your expecting is to get the columns alias instead of column name, so you have to use ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.
Get ResultSetMetaData using ResultSet#getMetaData():
ResultSetMetaData meta = rs.getMetaData();
And then to get column name of 1st column:
String col1Name = meta.getColumnLabel(1);
Similarly to get column name of 2nd column:
String col2Name = meta.getColumnLabel(2);
Get the metadata
ResultSetMetaData metaData = rs.getMetaData();
Then you can do:
String columnName = metaData.getColumnName(int index);
ResultSetMetaData doc
rs.getMetaData().getColumnName(int i);
and do not concat the query param!
In Java, after executing a query say I got a result set like:
bat 20 10
fat 20 5
cat 10 25
I want this resultset in a string such that the string will be:
bat,20,10 |fat,20,5 |cat,10,25
I am confused. How can I do that in Java?
ResultSet rs = ...
StringBuilder b = new StringBuilder();
while(rs.next()) {
String s = rs.getString(1);
int n1 = rs.getInt(2);
int n2 = rs.getInt(3);
b.append(s);
b.append(",");
b.append(n1);
b.append(",");
b.append(n2);
b.append("|");
}
while iterating through the resultset you can append its contents to a string ..right.?
String finalStr = "";
while(resultSet.next()){
finalStr+=resultSet.getString(1)+",";
finalStr+=resultSet.getInt(2).toString()+",";
finalStr+=resultSet.getInt(3).toString();
finalStr+="|";
}