Sql query that outputs to ONE Joptionpane - java

String sql = "SELECT TOP 10 id, Trailer, Block, Location, Day, SetTime, Comment FROM TrailerLocation"
+ " ORDER BY id DESC";
rs = st.executeQuery(sql);
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String trailer = rs.getString("Trailer");
String block = rs.getString("Block");
String location = rs.getString("Location");
String date = rs.getString("Day");
String comment = rs.getString("Comment");
//Display values
JOptionPane.showMessageDialog(null,
"ID: " + id
+ ", Trailer: " + trailer
+ ", Block: " + block
+ ", Location: " + location
+ ", Date & Time: " + date
+ ", Comment: " + comment);
}
I want the Joptionpane to only display once with all the data not ten times.

You could move the JOptionPane.showMessageDialog(null, ... ) after the while loop.
And, in the while loop, add the informations you want in one unique string which you will display in you JOptionPane.
rs = st.executeQuery(sql);
StringBuilder str = new StringBuilder();
while(rs.next()){
//Retrieve by column name
str.append("ID: " + rs.getInt("id"));
str.append(", Trailer: " + rs.getString("Trailer"));
str.append(", Block: " + rs.getString("Block"));
str.append(", Location: " + rs.getString("Location"));
str.append(", Date: " + rs.getString("Day"));
str.append(", Comment: " + rs.getString("Comment"));
//new line
str.append("\n");
}
JOptionPane.showMessageDialog(null,str.toString());

Related

JDBC incorrect syntax at or near "." executeQuery

This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'

Getting back movie ratings excluding my own

Basically, I have a table called ratings with 3 columns FILM, EMAIL, and RATING in mysql.
I can get back the average rating for all the films, but I must then display the ratings
of the movies that I haven't already rated , so I must only display all the films everybody else rated except me.
String email = Main_Login.accounttext.getText().trim();
statement = (PreparedStatement) con
.prepareStatement(""
+ "SELECT FILM,(film_total_ratings/number_of_ratings) as ratings_rating "
+ "FROM( "
+ "SELECT COUNT(*) as number_of_ratings, FILM, "
+ " SUM(RATING) as film_total_ratings "
+ " FROM ratings GROUP BY film "
+ "ORDER BY rating DESC"
+ ") TMP_Film");
result = (ResultSet) statement.executeQuery();
int i = 0;
while (result.next() && i <= 4) {
i++;
// if (result.getString(1).contains(email)) {
System.out.println((i) + ")" + " " + "[Movies You Might Like]"
+ " " + result.getString(1) + " " + "[Rating]" + " "
+ result.getString(2));
You may try to use CASE to add a column indicating that movie has been rated by the respective email or not. This is not tested but you may get the concept:
statement = (PreparedStatement) con
.prepareStatement(""
+ "SELECT FILM,(film_total_ratings/number_of_ratings) as ratings_rating "
+ "FROM( "
+ "SELECT COUNT(*) as number_of_ratings, FILM, "
+ " SUM(RATING) as film_total_ratings, "
+ " SUM(CASE WHEN EMAIL LIKE '%"+email+"%' THEN 1 ELSE 0 END) as rated"
+ " FROM ratings GROUP BY film HAVING rated=0 "
+ "ORDER BY rating DESC"
+ ") TMP_Film");

ResultSet with variable

Ok so basically I have this code:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
private void writeResultSet(ResultSet resultSet) throws SQLException {
System.out.println("jestem w writeresultset");
// resultSet is initialised before the first data set
while (resultSet.next()) {
// it is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g., resultSet.getSTring(2);
String id = resultSet.getString("id");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user
+ " nazwisko to " + website + " adres to " + summary + " email to "
+ date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
}
What I want to achieve is this:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS
where NAZWISKO LIKE " variable );
writeResultSet(resultSet);
I want to search by variable which is already defined, however I'm stuck and have no idea how to do it like that.
Use PreparedStatement:
String nazwisko = ...
String query = "select * from FEEDBACK.COMMENTS where NAZWISKO LIKE ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, nazwisko);
ResultSet rs = pstmt.execute();
while (resultSet.next()) {
//...
}
In case you need to use a wildcard for your LIKE, choose one of these:
nazwisko = nazwisko + "%";
nazwisko = "%" + nazwisko;
nazwisko = "%" + nazwisko + "%";
up , there are alot weird errors with your code:
like cannot find symbol variable con or incompatible type boolean cannot be converted to resultset.
I have tried this: but there is an error when executing
preparedStatement = connect
.prepareStatement("select * from FEEDBACK.COMMENTS where NAZWISKO= ? ; ");
preparedStatement.setString(1, surname3);
while (resultSet.next()) {
String id = resultSet.getString("i
d");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user + " nazwisko to " + website + " adres to " + summary + " email to " + date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
error:
the query went fine but , the error appears here "while (resultSet.next())"
SEVERE: null
java.lang.NullPointerException
at jdbcexample.Main.readDataBase(Main.java:416)
at jdbcexample.Main$7.mousePressed(Main.java:346)

Writing the resultset to csv file

I have a method getstaffinfo, which has 3 parameter (var_1, connection, filewriter fw), the var_1 value is read from a text file. So the method will be called as many times based on all the var_1 value passed from text file . approx ( 15000)
public static String getstaffid(String var_1, Connection connection,
FileWriter fw) throws SQLException, Exception
// Create a statement
{
String record = null;
ResultSet rs = null;
Statement stmt = connection.createStatement();
boolean empty = true;
try {
rs = stmt
.executeQuery("select username, firstname, lastname, middlename, street, city, stateorprovince, ziporpostalcode, countryorregion, fax, phone, extension, mobile, pager, title, primaryemail, secondaryemail, officename, description, comments, suspendeddate, userdata, employeeid, createuser, updateuser, createdate, updatedate, employeetype, servicedeskticketnumber, startdate, enddate, manager, businessapprover, technicalapprover, delegate, location, jobcodes, customproperty1, customproperty2, customproperty3, customproperty4, customproperty5, customproperty6, customproperty7, customproperty8, customproperty9, customproperty10 from globalusers where username = '"+ var_1 + "'");
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
ArrayList<String> records = new ArrayList<String>();
while (rs.next()) {
empty = false;
//record = rs.getString(1) + " " + rs.getString(2) + " " + rs.getString(3) + " " + rs.getString(4) + " " + rs.getString(5) + " " + rs.getString(6) + " " + rs.getString(7) + " " + rs.getString(8) + " " + rs.getString(9) + " " + rs.getString(10) + " " + rs.getString(11) + " " + rs.getString(12) + " " + rs.getString(13) + " " + rs.getString(14) + " " + rs.getString(15) + " " + rs.getString(16) + " " + rs.getString(17) + " " + rs.getString(18) + " " + rs.getString(19) + " " + rs.getString(20) + " " + rs.getString(21) + " " + rs.getString(22) + " " + rs.getString(23) + " " + rs.getString(24) + " " + rs.getString(25) + " " + rs.getString(26) + " " + rs.getString(27) + " " + rs.getString(28) + " " + rs.getString(29) + " " + rs.getString(30) + " " + rs.getString(31) + " " + rs.getString(32) + " " + rs.getString(33) + " " + rs.getString(34) + " " + rs.getString(35) + " " + rs.getString(36) + " " + rs.getString(37) + " " + rs.getString(38) + " " + rs.getString(39) + " " + rs.getString(40) + " " + rs.getString(41) + " " + rs.getString(42) + " " + rs.getString(43) + " " + rs.getString(44) + " " + rs.getString(45) + " " + rs.getString(46) + " " + rs.getString(47);
for (int i = 1; i <= columns; i++) {
String value = rs.getString(i);
records.add(value);
}
for (int j = 0; j < records.size(); j++) {
record = records.get(j) + ",";
}
fw.append(record);
}
/*fw.append(rs.getString(1));
fw.append(',');
fw.append(rs.getString(2));
fw.append(',');
fw.append(rs.getString(3));
fw.append('\n'); */
} finally {
fw.flush();
rs.close();
stmt.close();
}
return record;
}
As you can see, am executing a query for 47 values, which could be null or it can have some value.
Then i iterate through this 47 column, take the value and store it to an array list. Then i iterate the array list and write all the values to the string record with comma seperated value. Which is written to a csv file.
But it does not work fine. Any inputs would be appreciated...
You may have already solved the problem. Just let you know that I tried to use your code just now and found the issue was here:
record = records.get(j) + ",";
You should use something like this:
record = record + records.get(j) + ",";
Also change String to StringBuffer will improve the performance.
You didn't write the exact problem you face, but there is one for sure: you never write a line break into the file, so all data gets in one line.
while (rs.next()) {
... // your code, with the for loops
fw.append(record); //writing out the line, from your code
fw.append("\r\n"); //line break -- add this line
} //this is the end of the "while(rs.next())" loop
...

problem in finding the data

while i am finding the data the field of TelephoneNo showing the result in float like 54435435.0.even when i inserted this phone no as 54435435 my code is
String findby =cbfind.getSelectedItem().toString();
if(findby.equals("")){
JOptionPane.showMessageDialog(null," SELECT EITHER REGISTRATION NO OR NAME");
return;
}
if(findby.equals("RegNo"))
{
int regno1= Integer.parseInt(cbregn.getSelectedItem().toString());
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\n Driver loaded");
Connection con=DriverManager.getConnection("jdbc:odbc:wanisamajDB");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM REGISTRATION1 WHERE RegistrationNo="+regno1);
System.out.println("Hi");
rs.next();
String per = rs.getString("SeniorPerson");
System.out.println("SeniorPerson: " + per );
String reg = rs.getString("RegistrationNo");
System.out.println("RegistrationNo: " + reg);
String nplace = rs.getString("NativePlace");
System.out.println("NativePlace: " + nplace);
String kul = rs.getString("Kul");
System.out.println("Kul: " + kul);
String gtr = rs.getString("Gotra");
System.out.println("Gotra: " + gtr);
String ksami = rs.getString("KulSwami");
System.out.println("KulSwami: " + ksami);
String raddr = rs.getString("ResidensialAddress");
System.out.println("ResidensialAddress: " + raddr);
String code = rs.getString("PinCode");
System.out.println("PinCode: " + code);
String stdcd = rs.getString("STDcode");
System.out.println("STDcode: " + stdcd);
String teleno = rs.getString("TelephoneNo");
System.out.println("TelephoneNo: " + teleno);
String mno = rs.getString("MobileNo");
System.out.println("MobileNo: " + mno);
String email = rs.getString("Email");
System.out.println("Email: " + email);
String web = rs.getString("Website");
System.out.println("Website: " + web);
String educ = rs.getString("Education");
System.out.println("Education: " + educ);
String brch = rs.getString("Branch");
System.out.println("Branch: " + brch);
String bgrp = rs.getString("BloodGroup");
System.out.println("BloodGroup: " + bgrp);
JOptionPane.showMessageDialog(null, "RECORD FOUND");
cbnm.setSelectedItem(per);
tfplace.setText(nplace);
tfkul.setText(kul);
tfgotra.setText(gtr);
tfswami.setText(ksami);
taraddr.setText(raddr);
tfpcd.setText(code);
tfstdcode.setText(stdcd);
tftele.setText(teleno);
tfmno.setText(mno);
tfemail.setText(email);
tfweb.setText(web);
tfedu.setText(educ);
tfbrch.setText(brch);
cbbldgrp.setSelectedItem(bgrp);
}
catch (Exception e)
{
System.out.println("EXCEPTION " + e);
}
}
if(findby.equals("Name"))
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("\n Driver loaded");
Connection con=DriverManager.getConnection("jdbc:odbc:wanisamajDB");
Statement stmt=con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM REGISTRATION1 WHERE SeniorPerson='"+cbnm.getSelectedItem().toString()+"'");
System.out.println("Hi");
rs.next();
String per = rs.getString("SeniorPerson");
System.out.println("SeniorPerson: " + per );
String reg = rs.getString("RegistrationNo");
System.out.println("RegistrationNo: " + reg);
String nplace = rs.getString("NativePlace");
System.out.println("NativePlace: " + nplace);
String kul = rs.getString("Kul");
System.out.println("Kul: " + kul);
String gtr = rs.getString("Gotra");
System.out.println("Gotra: " + gtr);
String ksami = rs.getString("KulSwami");
System.out.println("KulSwami: " + ksami);
String raddr = rs.getString("ResidensialAddress");
System.out.println("ResidensialAddress: " + raddr);
String code = rs.getString("PinCode");
System.out.println("PinCode: " + code);
String stdcd = rs.getString("STDcode");
System.out.println("STDcode: " + stdcd);
String teleno = rs.getString("TelephoneNo");
System.out.println("TelephoneNo: " + teleno);
String mno = rs.getString("MobileNo");
System.out.println("MobileNo: " + mno);
String email = rs.getString("Email");
System.out.println("Email: " + email);
String web = rs.getString("Website");
System.out.println("Website: " + web);
String educ = rs.getString("Education");
System.out.println("Education: " + educ);
String brch = rs.getString("Branch");
System.out.println("Branch: " + brch);
String bgrp = rs.getString("BloodGroup");
System.out.println("BloodGroup: " + bgrp);
JOptionPane.showMessageDialog(null, "RECORD FOUND");
cbregn.setSelectedItem(reg);
tfplace.setText(nplace);
tfkul.setText(kul);
tfgotra.setText(gtr);
tfswami.setText(ksami);
taraddr.setText(raddr);
tfpcd.setText(code);
tfstdcode.setText(stdcd);
tftele.setText(teleno);
tfmno.setText(mno);
tfemail.setText(email);
tfweb.setText(web);
tfedu.setText(educ);
tfbrch.setText(brch);
cbbldgrp.setSelectedItem(bgrp);
}
catch (Exception e)
{
System.out.println("EXCEPTION " + e);
}
}//if
I'm going to wager that it's because that's how it's stored in the DB.
Use varchar rather than whatever it is you're using.
The answer you are seeing is most likely due to:
defining the column type for the telephone number to be "float", "double", "decimal", "numeric" or "real", or
defining the column type as "char", "varchar", etc and populating it from a Java float, double or BigDecimal.
In either case, what you are seeing reflects the data stored in the database.

Categories