Basically, I have to show a list with the data from a database table [that part is working] and afterwards I have to show the highest Date [a date variable in the table]. The second part is not working no matter what I do.
Here's the code
try {
String SQL = "SELECT * FROM tb_rafael";
ResultSet rs = BD.consultar(SQL);
String tab = "";
int numReg = 0;
while (rs.next()) {
tab+="<TR>";
tab+="<TD>" + rs.getString("nme_rafael") + "</TD>";
tab+="<TD>" + rs.getString("dta_rafael") + "</TD>";
tab+="</TR>";
numReg++;
//mDat = rs2.getString("dta_rafael");
}
rs.close();
dados.put("DADOS", tab);
dados.put("NUM_REG", String.valueOf(numReg));
//Pegar Data Maior
String SQL2 = "SELECT MAX(dta_rafael) FROM tb_rafael";
ResultSet rs2 = BD.consultar(SQL2);
String mDat = "";
//while(rs2.next()){
mDat = rs2.getString("dta_rafael");
//}
rs2.close();
dados.put("MDA", mDat);
} catch (Exception ex) {
dados.put("MSG", "Erro: " + ex.getMessage());
}
What you want to look at is past the commentary line "Pegar Data Maior". That's the part that is not working. I've tried adding a while, using a different ResultSet, using the same ResultSet and none of those worked. I know it's not an issue with the SQL query since I tested it with the workbench and it returned me the data I want.
To be more specific, I don't get an error message or anything, the dados.put simply does not work and I get just this:
How the HTML code looks:
The data should show up where the {MDA} is. Anyone have any ideas?
The query SELECT MAX(dta_rafael) FROM tb_rafael may not return a column name, which you later try to retrieve, rs2.getString("dta_rafael");
I'd change the query to SELECT MAX(dta_rafael) AS Max_date..., and reference to MAX_date thereafter.
Related
Submitting a query from SQLiteStudio returns the expected result from a View.
However, when the same query is sent from my program in java, the result is different for some queries.
ie: SELECT Rev FROM PartRevs WHERE PartNumber = '800111'
This returns the expected result of "B" when executed within SQLiteStudio. However, then the same query is executed from JAVA, it returns "A". Only one result is returned with both queries.
This does not happen consistently. Most queries work, but it occasionally does not work.
The 'Rev' or Revision of a given part is pulled from another table called 'ECO_TDA_Linewise'. Each time a new revision is released for a given part, a new line is added with increasing index numbers.
I believe the problem comes from the way the 'PartRevs' view works. Of the many other tables and queries, this is the only one that has an issue.
Here are the code blocks that interact with the database:
public String GetRevision(String PartNumber) {
String sqlStatement = "SELECT Rev FROM PartRevs WHERE PartNumber = '" + PartNumber + "'";
return getDatabaseResult(sqlStatement, "Rev");
}
public String getDatabaseResult(String sqlStatement, String Column) {
String result = "";
try (Connection conn = FulfillmentWorkorders.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sqlStatement)) {
result = rs.getString(Column);
conn.close();
} catch (SQLException e) {
System.out.println("\"" + sqlStatement + "\" throws exception: " + e.getMessage());
}
return result;
}
I'm using JFreeChart to create a chart in Java and MySQL.
When I try to insert my values in another table the query seems to be executed twice since I end up with the same timestamps multiple times...
Here's a part of my code :
private JDBCXYDataset createDataset() {
try {
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost:bd?serverTimezone=UTC","MySQL", "MySQL");
conn.setAutoCommit(false);
SQLException savedException = null;
Statement st = conn.createStatement();
st.execute("DROP TABLE IF EXISTS test ");
st.execute("create table test(Table timestamp, Table float,Table float)");
String Date_Debut = "2020-06-25 00:00:00";
String Date_Fin = "2020-06-26 00:00:00";
String sql1 = "INSERT INTO test (Table ,Table ,Table ) "
+ "SELECT Table ,Table ,Table "
+ "FROM Table "
+ "WHERE Table BETWEEN ? AND ? ";
try ( PreparedStatement ps = conn.prepareStatement(sql1)){
ps.setString(1,Date_Debut);
ps.setString(2, Date_Fin);
ps.executeUpdate();
ps.close();
JDBCXYDataset jds = new JDBCXYDataset(conn);
st.close();
jds.executeQuery("SELECT Table ,Table ,Table FROM test");
conn.commit();
return jds;
} catch (SQLException ex) {
savedException = ex;
conn.rollback();
} finally {
conn.setAutoCommit(true);
if(savedException != null) {
throw savedException;
}
}
} catch (SQLException ex1) {
}
return null;
}
EDIT : Actually it seems like the errors where comming directly from the database, the moderators can delete this post if they want. However I keep Trashgod's response validated as it was more than helpful.
For everyone that might come here with a similar issue, inspect in detail your database first to see if it isn't comming from there instead of your code.
Chasing down anomalies in data is arduous, but JFreeChart can at least make the result easier to visualize. Some heuristics for testing:
To verify that the the presumed duplicates in your tabular listing are indeed duplicates, format the timestamps to include milliseconds, e.g. add an S to a SimpleDateFormat or A to a DateTimeFormatter.
For study, temporarily pass the query directly to JDBCXYDataset, and add an ORDER BY clause (untested):
jds.executeQuery(
"SELECT Date_Heure, PV, SV FROM cmd3 "
+ "WHERE Date_Heure BETWEEN "
+ "2020-06-25 00:00:00 AND 2020-06-26 00:00:00 "
+ "ORDER BY Date_Heure");
Enable tooltips in your ChartFactory, as you did here, to see data values in situ. This may suggest additional conditions for your WHERE clause, e.g. PV BETWEEN 5.1 AND 5.9.
Use the interactive JFreeChart pan/zoom controls, discussed here to examine the data; add suitable buttons, shown here, if it will make it easier for colleagues to see your findings.
By design, JDBCXYDataset executes a query defined by a String. If your design needs to display data from a query defined by a PreparedStatement, you can use the existing implementation as a guide.
public class PreparedDataset extends AbstractXYDataset
implements XYDataset, TableXYDataset, RangeInfo {
private final PreparedStatement ps;
public PreparedDataset(PreparedStatement ps) {
this.ps = ps;
}
…
}
I'm a java beginner and struggle with two problems.
1) The SQL Exception: no such column 'Ofen'
This is my Code and I want to get specific data from a SQLite Database called "kleintest.db" with 2 tables "maindata" and "Zahlwertuntertable". maindata contains the 'Ofen' entry as TEXT. The ResultSet rs should generally take all Data from maindata and the ResultSet rs2 should take the weight from Zahlwertuntertable. But running the programm now shows the mentioned error.
public static void readDB() {
try {
Statement stmt = connection.createStatement();
//ResultSet rs = stmt.executeQuery("SELECT * FROM Gewichtsabnahme;");
ResultSet rs = stmt.executeQuery("SELECT * FROM maindata;");
ResultSet rs2 = stmt.executeQuery("SELECT * FROM Zahlwertuntertable;");
while (rs.next()) {
System.out.println("Ofen = " + rs.getString("Ofen"));
System.out.println("Platznummer = " + rs.getInt("Zahlwert"));
System.out.println("Startdatum = " + rs.getString("Startdatum"));
LocalDate heute = LocalDate.now();
String Datum = rs.getString("Startdatum");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
LocalDate Wägetag = LocalDate.parse(Datum, formatter);
Period DiffTag = Period.between(heute, Wägetag);
System.out.format("Tage = " + DiffTag.getDays() + "\n"); //
System.out.println("Gewicht = " + rs2.getInt("Startgewicht"));
}
rs.close();
rs2.close();
connection.close();
} catch (SQLException e) {
System.err.println("Zugriff auf DB nicht möglich.");
e.printStackTrace();
}
}
The table maindata contains the following items:
Laufnummer Ofen Zahlwert Startdatum
But Laufnummer is just a primary key and should not be retrieved.
2) Next Question is the thing with the Period function. This worked well but as a printed result I'll get P 1D or P 1M 2D what looks slightly confusing. I like to print just the simple amount of days like 45 or 45D and added the getDays() to my DiffTag. Now my result is -1 what makes no sense at all. What's wrong here?
Period DiffTag = Period.between(heute, Wägetag);
System.out.format("Tage = " + DiffTag.getDays() + "\n");
Thanks for suggestions and links I may have missed. But everything I looked so far didn't point out my specific questions.
You can only have one result set open at a time for a Statement object so when you execute the second query agains "Zahlwertuntertable" the first one gets closed.
So either add another statement or handle one query at a time.
Also, right now it looks strange that you call rs.next() but never rs2.next()
This is driving me mad because I cannot make any sense of it. I am executing the following code:
nameString = jcbClientList.getItemAt(jcbClientList.getSelectedIndex());
System.out.println(" Name String = " + nameString );
sql = "SELECT * FROM clients WHERE Name = \'" + nameString + "\'";
System.out.println(sql);
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while( rs.next()) {
clientID = rs.getInt(1);
}
}
catch(SQLException se) {
msg = "Problem getting client ID from DB \n" + se.getLocalizedMessage();
System.out.println(msg);
JOptionPane.showMessageDialog(null, msg);
}
The SQL string be built is correct. I have checked this by taking the System.out.println(sql) output of the string and pasting it into other code and it work perfectly. However, in this context I am getting an exception:
Invalid cursor state - no current row.
Even if I change the sql to be 'SELECT * FROM clients' which should return 20 rows and does elsewhere in the application, it still gives the same error. The database being addressed is an embedded Derby DB.
I seem to recall having run into specific JDBC drivers that did not properly implement the part that says " A ResultSet cursor is initially positioned before the first row ". I got around it by first doing a first() (or beforeFirst()) call and only then start invoking next().
I have a mysql table user which is consisted of id, name, password and email columns.
Is there a way to create some sort of query or java code that will print in my message dialog window all of the users names.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
if (rs.next()) {
val1 = rs.getString(2);
val2 = rs.getString(3);
}
value = val1 + " " + val2;
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
This only prints the name and the surname of the first user from the table :(
I want to print them all one below another!
If I set rs.getString(5); - it gives me an error: column index out of range.
I suggest you avoid JOptionPane for this kind of code. Better to use some Frame (Swing) and display all of the users into a separate window.
The problem with your code is that variable value is lyiong outside of the loop (which must be btw while loop, as spencer said).
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/mydb","root","");
String sql = "select * from user;";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
val = rs.getString(2) + " " + rs.getString(3);
value += val + " ";
}
JOptionPane.showMessageDialog(null,value);
}catch(SQLException e){
JOptionPane.showMessageDialog(null, e);
}
}
Try to avoid this type of code, use ArrayList and save in the array all of the users credentials. Then easily label it wherever you want.
You're only fetching the first row from the resultset. It sounds like you want a loop, and process every row from the resultset.
while (rs.next()) {
}
UPDATE
Q: It only gives me now the last user. Probably because it overwrites the val1 and val2 variable. I suppose somehow this should also goes into the loop..
A: Yes, it should go inside the loop. But I'd be populating a collection, rather than concatenating a String.
As a performance and maintenance note, you can avoid the messiness of the string concatenation in the Java by doing the concatenation in the SQL statement. I wouldn't use SELECT * and rely on the positions of two particular columns in the resultset.
I'd use a SQL statement like this:
SELECT CONCAT(u.first_name,' ',u.last_name) AS user_name FROM users
If I wasn't populating a collection, and I needed to concatenate a honkous string, I'd use a StringBuffer, e.g.
val = new StringBuffer(4096));
while (rs.next()) {
val.append(rs.getString("user_name"));
}
value = val.toString;