Java mysql next result from stored procedure - java
I have following stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `blast10`()
BEGIN
SELECT concat("ROUND ",draws.izvlacenje_id,": ", draws.1,",",draws.2,",",draws.3,",",draws.4,",",draws.5,",",draws.6,",",draws.7,",",draws.8,",",draws.9,",",draws.10,",",draws.11,",",draws.12,",",draws.13,",",draws.14,",\n",draws.15,",",draws.16,",",draws.17,",",draws.18,",",draws.19,",",draws.20,",",
draws.21,",",draws.22,",",draws.23,",",draws.24,",",draws.25,",",draws.26,",",draws.27,",",draws.28,",",draws.29,",",draws.30,",",draws.31,",",draws.32,",",draws.33,",",draws.34,",",draws.35,"")
rzlt from macau.draws order by iddraws desc limit 10;
END`
This procedure returns 10 rows of data and i want to send that data through TCP/IP communication, this is what i achieved by now:
public void blastTen() throws SQLException {
String blastTen = "";
String bl10 = "LAST 10 RESULTS";
try {
Statement st = Conex.conn.createStatement();
String SQLEdit = "{ call blast10() }";
ResultSet rs = st.executeQuery(SQLEdit);
while (rs.next()) {
blastTen = bl10 + "\n" + rs.getString("rzlt") + "\n";
}
os.println(blastTen + "\n");
}
catch (Exception e2) {
System.out.println(e2);
}
}
The problem is I can send only one row and can't seem to get the other rows.
Any help is appreciated
The code
while (rs.next())
{
blastTen=bl10+"\n"+rs.getString("rzlt")+"\n";
}
won't assign anything to bl10 so you'll always only get the latest row... Try
...
bl10 = bl10 + "\n" + rs.getString( "rzlt" );
}
os.println( bl10 );
instead.
Cheers,
Related
SQL command not properly ended with select
I'm working with Oracle SQL Developer with a Java application. I want to ask to the DB this query: select * from vocabolario, vocaboli_help where verbo=1 and vocabolario.id = vocaboli_help.id and vocaboli_help.usato = 0 The query works when I run it from SQL developer, but when run it from Eclipse with the stmt.executeQuery(string), where stmt is a Statement object, it throws the following exception: SQL command not properly ended. I put also a semicolon at the end of the string, but it doesn't work. I used the stmt.executeQuery(string) with other queries and in those cases there were no problems. The only difference I can see is that in this case I have where condition in AND. Java code : private final static String NOME_DATABASE = "VOCABOLARIO", NOME_DATABASE_HELP ="VOCABOLI_HELP"; String type ="verbo"; String query = "SELECT * FROM " + NOME_DATABASE + ", " + NOME_DATABASE_HELP +" WHERE " + type + " = 1 " + "AND " + NOME_DATABASE +".ID = " + NOME_DATABASE_HELP +".ID AND "+NOME_DATABASE_HELP+".USATO = 0"; System.out.println(query); int cont = 0; String result=""; try { ResultSet res = statement.executeQuery(query); while(res.next()) { String cod = res.getString("ID").trim(); String voc = res.getString("VOCABOLO").trim(); String trad = res.getString("TRADUZIONE").trim(); if(cont == n) result = cod + "," + voc + "," + trad; cont++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; `
select * from vocabolario vo left join vocaboli_help voh on vo.id= voh.id where v.verbo=1 AND voh.usato=0 You just need a simple join. VOCABOLI_HELP or vocabolario_help your code and your post different
Thank you all, the problem was in the name of the second table, but I think it depends on Java code sintax, as #are suggested. I updated the code: private static final String NOME_DATABASE_HELP = "VOCABOLIHELP" I also modified the table name in the DB and now it works. I think there are issues with the underscore in the name (the problem is only in Java as I said), I don't know why.
i want to display special characters from mysql to jtextfield using jbutton.my code is working only numbers
private void jbutton1ActionPerformed(java.awt.event.ActionEvent evt) { try { MainClass mc=new MainClass(); Connection connection; connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd); ResultSet rs; String StrQr=""; if (prid.getText().trim().length()>0 ) { StrQr=StrQr + " and pid = " + prid.getText().trim() + " "; } if (StrQr.length()==0) { JOptionPane.showMessageDialog(null,"Enter search critaria."); return; } PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid"); rs = st.executeQuery(); JOptionPane.showMessageDialog(null,"connected"); while (rs.next()) { purcst.setText(rs.getString("ppurcst")); salprc.setText(rs.getString("psalprc")); prid.setText(rs.getString("Pid")); prname.setText(rs.getString("Pname")); category.setText(rs.getString("Pcategory")); cprc.setText(rs.getString("Pcmprc")); qnty.setText(rs.getString("Pqty")); slno.setText(rs.getString("Pslno")); lpurcst.setText(rs.getString("plpurcst")); } rs.close(); } catch (Exception e) { System.err.println(e); //System.exit(1); } } code display only pid = 104 like numbers . it cant display special charectors( _,- )pid= A_1103like anybody can help me. com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Unknown column 'A' in 'where clause' i declare pid as varchar in mysql
A_1103 needs to be quoted, otherwise MySQL will try and resolve it to a column value. ... pid = 'A_1103' ... In fact, you should be relying on PreparedStatement in order to prevent possible SQL injection problems. See Using Prepared Statements for more details For example... Connection connection; connection=DriverManager.getConnection(mc.StrUrl,mc.StrUid,mc.StrPwd); ResultSet rs; // I'm assuming there are other elements to this query that // may be included, otherwise this is a lot of overhead // for little benifi... List values = new ArrayList(5); String StrQr=""; if (prid.getText().trim().length()>0 ) { StrQr += " and pid = ? "; values.add(prid.getText().trim()); } if (StrQr.length()==0) { JOptionPane.showMessageDialog(null,"Enter search critaria."); return; } PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid"); // Bind the values to the parameters for (int index = 0; index < values.size(); index++) { st.setObject(index + 1, values.get(index)); } rs = st.executeQuery(); JOptionPane.showMessageDialog(null,"connected");
In prepared statement you have to set a ? or any parameter and bind the value. String StrQr=""; if (prid.getText().trim().length()>0 ) { StrQr=StrQr + " and pid = ? "; } ... PreparedStatement st=connection.prepareStatement("select pid, pname,pslno,pcategory,pqty,ppurcst,plpurcst,psalprc,pcmprc from addproducts where 1=1 " + StrQr + " order by pid"); if (prid.getText().trim().length()>0 ) st.bind(1prid.getText().trim() ) rs = st.executeQuery(); JOptionPane.showMessageDialog(null,"connected");
Exception when trying to create a trigger using SQLQuery [duplicate]
i've got some code that is triggering a syntax error because of some misplaced semicolons. if this was running on the command line, i'd solve this with a delimiter. unfortunately, the jdbc4 driver doesn't seem to recognize delimiters. anyway to get this to run? delimiter | CREATE TRIGGER obs_update BEFORE UPDATE ON obs FOR EACH ROW BEGIN IF OLD.voided = 0 AND NEW.voided = 1 THEN DELETE FROM clinic_obs WHERE id = OLD.obs_id; ELSE UPDATE clinic_obs SET clinic_obs.revision_token = NOW() WHERE NEW.obs_id = clinic_obs.id; END IF; END; | delimiter ;
Delimiter is a command for SQL client. There is no need to use delimiter in JDBC. Example below shows it: import java.sql.*; public class TriggerExample { public static void main(String args[]) { String connectionURL = "jdbc:mysql://localhost:3306/test"; Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(connectionURL, "login", "password"); Statement stmt = con.createStatement(); stmt.execute("CREATE TRIGGER obs_update BEFORE UPDATE ON obs " + "FOR EACH ROW " + "BEGIN " + "IF OLD.voided = 0 AND NEW.voided = 1 THEN " + " DELETE FROM clinic_obs WHERE id = OLD.obs_id; " + "ELSE " + " UPDATE clinic_obs SET clinic_obs.revision_token = NOW() " + " WHERE NEW.id = clinic_obs.id; " + "END IF; " + "END;"); con.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (con != null) { try { con.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
Try removing the semi colon after the final END word. so it looks like this: delimiter | CREATE TRIGGER obs_update BEFORE UPDATE ON obs FOR EACH ROW BEGIN IF OLD.voided = 0 AND NEW.voided = 1 THEN DELETE FROM clinic_obs WHERE id = OLD.obs_id; ELSE UPDATE clinic_obs SET clinic_obs.revision_token = NOW() WHERE NEW.obs_id = clinic_obs.id; END IF; END| It should work because I have done a similar trigger/procedure using jdbc driver.
JDBC's rs.getString() won't return the value of the query result
I have some problems with JDBC's rs.getString("column_name") basically it would not assign the value recieved from the query result, I have a String ris which is supposed to get the row name from rs.getString, for semplicity of the question I'm using ris and my query returns only one row. This is the code: //It returns null, or any other values I use to initialize the variable String ris=null; q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")"; ResultSet rs = st.executeQuery(q); if (!rs.last()) { ris = "no"; } else { //This is the place where I'm having problems while(rs.next()){ //ris is supposed to get the name of the query result having column "nome" ris=rs.getString("nome"); } } conn.close(); } catch (Exception e) { ris = e.toString(); } return ris; I semplified the code, so it would be easy to focus on where the problem is. Thanks in advance!
if (rs.last()) while (rs.next()) That won't work, because after you have called last , you are at the last row and next will always return false (it would return true and take you to the next row if there was one left). And please use a prepared statement with bind variables! And finally close ResultSet and Connection (or use Jakarta Commons DbUtils).
try this, just remove the rs.last() call in the if condition.. also i agree with #Thilo about using prepared statements. String ris=null; q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")"; ResultSet rs = st.executeQuery(q); rs.first(); // go to first record. //This is the place where I'm having problems while(rs.next()){ //ris is supposed to get the name of the query result having column "nome" ris=rs.getString("nome"); } } conn.close();
Nested SELECT Query Java + MySQL
I'm trying to get data from DB. I must use to queries. From the first query (In Loop) I get the code of Work codew and the I use it in the second query to get names. Here's the code works without errors. The first query fetch rows but the second is not executed. int i=0; c= new Connect().getCon(); try{ java.sql.Statement st = c.createStatement(); String sql= " SELECT distinct(s.codew), title, nberstat, desc_w, dated,datef" + " FROM work w, employe e, stat s " + " WHERE w.codew=s.codew " + " and s.idemploye= e.idemploye " + " and stat_w=0 " + " and w.idcreator= 1"; System.out.println(sql); ResultSet res = (ResultSet) st.executeQuery(sql); String allW =""; while (res.next()) { String codew = res.getString("codew"); String title = res.getString("title"); String desc_w = res.getString("desc_w"); String dated = res.getString("dated"); String date = res.getString("datef"); int nberstat = res.getInt("nberstat"); String strnberstat = Integer.toString(nberstat); /////////////////////////////////// try { java.sql.Statement st2 = c.createStatement(); q="SELECT distinct (name), lname From stat s, employe e WHERE codew LIKE '"+codew+"'"; ResultSet res2 = (ResultSet) st2.executeQuery(q); while (res2.next()) { String name = res.getString("name"); String lname = res.getString("lname"); allW = name + " "+lname+", "+allW; } } catch (SQLException s) { System.out.println("SQL code does not execute."); } ///////////////////////////// ........ } c.close(); } catch (SQLException s){ System.out.println("SQL code does not execute."); } I get this in the console for the second query! SQL code does not execute. Thanks in advance. Best regards, Ali
First of all you should use PreparedStatement with sql parameters "?" to prevent Sql injections. Secondly, you are using the wrong statement in the second loop. You should be using res2 not res. This should be: String name = res2.getString("name"); //not res String lname = res2.getString("lname"); //not res Thirdly, you should add a finally{} block and close your connection.