2014-07-09 9 views
7

Come passare la variabile stringa java nella query sql. Ho eseguito tutte le connessioni JDBC.passando la variabile stringa java nella query mysql

My SQL query di database è

sql = "Select * 
     from production AS cust 
     INNER JOIN location AS comp 
     ON cust.location_id = comp.location_id 
     where comp.name = locationnames AND crop_id =1"; 

Non sta funzionando. Tuttavia, se faccio il seguente codice relativo funzionamento

sql = "Select * 
     from production AS cust 
     INNER JOIN location AS comp 
     ON cust.location_id = comp.location_id 
     where comp.name = "\taplejung"\ 
     AND crop_id =1"; 

Ora ditemi come devo passare il nome variabile per la query SQL per eseguire questo. Jst dimmi come passare la variabile locationnames in comp.name.

La mia funzione java completa si presenta così: locationCombo denota l'elemento selezionato in combobox. CropCombo denota anche la stessa ...

public void displayYearwise() throws SQLException, ClassNotFoundException{ 

     //jComboBox4.setSelectedItem("Crops"); 
     //DefaultCategoryDataset dataset = new DefaultCategoryDataset(); 
     XYSeriesCollection dataset = new XYSeriesCollection(); 
     XYSeries series = new XYSeries("production"); 
     XYSeries series1 = new XYSeries("scat"); 
     String JDBC_DRIVER="com.mysql.jdbc.Driver"; 
    String DB_URL="jdbc:mysql://localhost/data2"; 
    Connection conn; 
    Statement stmt; 
    String USER = "root"; 
    String PASS = ""; 
     Object cropname = CropCombo.getSelectedItem(); 
     String cropnames = cropname.toString(); 
     Object locationname = locationCombo.getSelectedItem(); 
     //  String locationnames = locationname.toString(); 
     String locationnames = "taplejung"; 
     String pd="paddy "; 
      System.out.println(cropnames.length()+" "+pd.length()); 

      System.out.println(cropsList); 
     String sql=null; 
     if(cropnames.equals("paddy")) 
     { 
      //System.out.println();      
      sql="Select * 
        from production AS cust 
        INNER JOIN location AS comp 
        ON cust.location_id = comp.location_id 
        WHERE comp.name = "+locationnames+" 
        AND crop_id =1"; 
     } 


      else{ 
      sql="SELECT * 
       FROM `production` 
       WHERE crop_id = 4 
       AND location_id = 10"; 
     } 

      try{ 
      Class.forName(JDBC_DRIVER); 
      conn=DriverManager.getConnection(DB_URL,USER,PASS); 
      System.out.println("Creating statement..."); 
      stmt = conn.createStatement();      
         System.out.println(sql);    
         ResultSet rs=stmt.executeQuery(sql);      
         while (rs.next()){ 
          //String student = rs.getString("studentname"); 
          String yeartext = rs.getString("year_of_production"); 
          //double value = Double.parseDouble(text); 
          String productiontext = rs.getString("production_amount"); 
          Double yield = rs.getDouble("yield_amount"); 
          double production = Double.parseDouble(productiontext); 
          double year = Double.parseDouble(yeartext); 
          series.add(year,production) ; 
          series1.add(year,yield) ; 
          //dataset.addSeries(series);    
      } 
         dataset.addSeries(series); 
         dataset.addSeries(series1);  
         chartArea.removeAll(); 
         JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset); 
         // JFreeChart chart = ChartFactory.createScatterPlot("Scatter Plot","Year","Paddy Production", dataset, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled); 
//      CategoryPlot p = chart.getCategoryPlot(); 
         //XYPlot xyplot = (XYPlot)jfreechart.getPlot(); 
         //http://stackoverflow.com/questions/12417732/jfreechart-with-scroller 
         ChartPanel chartPanel = new ChartPanel(chart, false); 
         chartArea.setLayout(new BorderLayout()); 
         chartArea.add(chartPanel, BorderLayout.EAST); 
         chartArea.add(chartPanel); 
         SwingUtilities.updateComponentTreeUI(this); 
//      p.setRangeGridlinePaint(blue); 
         chartArea.updateUI(); 
         System.out.println("Database created successfully..."); 

       } 
      catch(SQLException se) 
       { 
        //Handle errors for JDBC 
        System.out.println("Connect failed ! "); 
        se.printStackTrace(); 
//     JOptionPane.showMessageDialog(MajorUI.this, err.getMessage()); 
        } 

    } 

risposta

4

Utilizzare un PreparedStatement e associare il parametro String,

final String sql = "select * from production AS cust INNER JOIN location" 
    + " AS comp ON cust.location_id = comp.location_id where " 
    + "comp.name = ? AND crop_id = 1"; 
PreparedStatement ps = null; 
try { 
    ps = conn.prepareStatement(sql); 
    ps.setString(1, "taplejung"); 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    if (ps != null) { 
    try { 
     ps.close(); 
    } catch (Exception ignored) { 
    } 
    } 
} 

Modifica (Basato sul codice aggiuntivo, modificarlo a qualcosa di simile)

PreparedStatement ps = null; 

String sql = null; 
if (cropnames.equals("paddy")) { 
    // System.out.println(); 
    sql = "SELECT * FROM `production` AS cust INNER JOIN location AS comp " 
     + "ON cust.location_id = comp.location_id WHERE comp.name = " 
     + "? AND crop_id = 1"; 
} else { 
    sql = "SELECT * FROM `production` WHERE crop_id = 4 AND location_id = 10"; 
} 
ps = conn.prepareStatement(sql); 
if (cropnames.equals("paddy")) { 
    ps.setString(1, locationnames); 
} 
System.out.println(sql); 
ResultSet rs = ps.executeQuery(); 
+1

PrepareStatement è sicuro anche da SQL injection. Maggiori dettagli su http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html –

+0

@Elliott Frisch ... ho tutto il codice sql funzionante in java. Non è che ho solo bisogno di taplejung. Il nome della posizione viene importato dalla casella combinata in java. La casella combinata è connessa al database mysql per ottenere il nome della posizione. Voglio semplicemente passare il nome della variabile a sql query. Potresti vedere la mia domanda ancora una volta ... vedi la mia domanda – enjal

+0

@ElliottFrisch pensi di potermi aiutare nel mio codice. ? Puoi dirmi cosa ho fatto di sbagliato? Il problema è semplicemente nella query sql per passare la variabile java .. come dovrei passare la variabile java – enjal

4
String locationnames = "taplejung"; 

String sql = "Select * from production AS cust INNER JOIN location AS comp ON cust.location_id = comp.location_id where comp.name ='"+ locationnames +"' AND crop_id =1"; 
+1

o utilizzare un 'PreparedStatement' ... – MadProgrammer

+0

@Bishan l'ho fatto ii ottenere il seguente errore. Seleziona * dalla produzione AS cust INNER JOIN posizione AS comp ON cust.location_id = comp.location_id WHERE comp.name = Taplejung AND crop_id = 1 Connessione fallita! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown colonna 'Taplejung' in 'where clause' \t a sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Native Method) – enjal

+0

provato questo uno? '" Seleziona * dalla produzione AS cust INNER JOIN posizione AS comp ON cust.location_id = comp.location_id dove comp.name = '"+ locationnames +"' AND crop_id = 1 "' – Bishan

0

Ogni volta che ho per creare query sql uso una libreria come jdbi per farlo. Questo ti permetterà di creare un'interfaccia con diverse query. Tutto ciò che devi fare è definire l'interfaccia, creare un POJO e creare un mapper tra una tabella SQL e un POJO Java.

L'interfaccia sarebbe simile a questa.

@RegisterMapper(ProductionMapper.class) 
public interface ProductionDAO { 
    @SqlQuery("Select * from production AS cust INNER JOIN location AS comp ON cust.location_id = comp.location_id where comp.name = :name AND crop_id =1") 
    Production findRow(@Bind("name") String name); 
    } 

Il POJO sarebbe simile a questo.

public class Production { 
    private VariableTypeA variableA; 
    // other variables 
    public Production(VariableTypeA variableA ....) { 
     this.variableA = variableA; 
     // set everything else 
    } 
    // getters and setters 
} 

Il mapper sarebbe simile a questo.

public class ProductionMapper implements ResultSetMapper<Production> { 
    public Production map(int index, ResultSet r, StatementContext ctx) throws SQLException { 
    return new Production(r.getSomeType("columnName"), ...); 
    } 
} 

Questo design lo rende molto semplice per interagire con il database e passare le variabili così come fare in modo che le vostre classi dont violare la SRP

http://jdbi.org/sql_object_overview/

0

variabile passa è tranquilla semplice in mysql query usando java.

  • Scrivi la richiesta
  • e scrivere la variabile in ""
  • Nel mio caso sto passando 'conition' e 'nometabella' in modo dinamico.
  • Grazie mille buona giornata.

    @Override pubblico LinkedList getNameList (condizione String, String tableName, String projectName) {// metodo TODO generato automaticamente stub

    String query = "select distinct("+condition+") as name from "+tableName+" "; 
    
    //System.out.println(query); 
    
    ResultSet rs = null; 
    PreparedStatement preparedStatement = null; 
    Connection connection = null; 
    
    LinkedList finalList = new LinkedList(); 
    try{ 
        connection = dataSourceAbacus.getConnection(); 
        preparedStatement = connection.prepareStatement(query); 
        rs= preparedStatement.executeQuery(); 
        while(rs.next()){ 
    
         finalList.add(rs.getString("name")); 
        } 
    }catch(Exception e){ 
        e.printStackTrace(); 
    }finally{ 
        if(connection !=null){ 
         try { 
          connection.close(); 
         } catch (SQLException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
        } 
        if(preparedStatement != null){ 
         try{ 
          preparedStatement.close(); 
         }catch(Exception e){ 
          e.printStackTrace(); 
         } 
        } 
        if(rs != null){ 
         try{ 
          rs.close(); 
         }catch(Exception e){ 
          e.printStackTrace(); 
         } 
        } 
    } 
    
    return finalList; 
    

    }

Problemi correlati