2014-07-09 4 views
7

Comment passer la variable de chaîne java dans la requête sql. J'ai effectué toutes les connexions JDBC.passant la variable de chaîne java dans la requête mysql

Ma base de données de requêtes SQL est

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"; 

Il ne fonctionne pas. Toutefois, si je fais le code suivant son travail

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"; 

Maintenant, dites-moi comment dois-je passer nom de la variable à la requête SQL pour exécuter ce. Jst dites-moi comment passer la variable locationnames à comp.name.

Ma fonction Java complète ressemble à ceci: locationCombo indique un élément sélectionné dans la liste déroulante. CropCombo indique aussi le même ...

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()); 
        } 

    } 

Répondre

4

Utilisez un PreparedStatement et lier le paramètre 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) { 
    } 
    } 
} 

Modifier (En fonction de votre code supplémentaire, changer quelque chose comme)

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 est aussi sûr de l'injection SQL. Plus de détails sur http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html –

+0

@Elliott Frisch ... j'ai tout le code SQL de travail en Java. Ce n'est pas que j'ai seulement besoin de taplejung. Le nom de l'emplacement est importé à partir de la zone de liste déroulante dans java. La zone de liste déroulante est connectée à la base de données mysql pour l'obtention de locationname. Je veux simplement passer le nom de la variable à sql query.may être vous pourriez voir ma question une fois de plus .. voir ma requête – enjal

+0

@ElliottFrisch pensez-vous que vous pourriez m'aider dans mon code. ? Pouvez-vous me dire ce que j'ai mal fait? Le problème est simplement dans sql query pour passer la variable java .. comment dois-je passer la variable 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

Ou utiliser un 'PreparedStatement' ... – MadProgrammer

+0

@Bishan je l'ai fait ii obtenir l'erreur suivante. Sélectionnez * depuis la production AS cust INNER JOIN emplacement AS comp SUR cust.location_id = comp.location_id WHERE comp.name = Taplejung AND crop_id = 1 Connexion échouée! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Colonne inconnue 'Taplejung' dans 'where clause' \t at sun.reflect.NativeConstructorAccessorImpl.newInstance0 (Méthode native) – enjal

+0

Vous avez essayé celui-ci? '" Sélectionnez * depuis la production AS cust INNER JOIN emplacement AS comp SUR cust.location_id = comp.location_id où comp.name = '"+ locationnames +"' AND crop_id = 1 "' – Bishan

0

Chaque fois que j'ai Pour faire des requêtes sql, j'utilise une bibliothèque comme jdbi pour le faire. Cela vous permettra de créer une interface avec différentes requêtes. Tout ce que vous avez à faire est de définir l'interface, de créer un POJO et de créer un mappeur entre une table SQL et un POJO Java.

L'interface ressemblerait à ceci.

@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); 
    } 

Le POJO ressemblerait à ceci.

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

Le mappeur ressemblerait à ceci.

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

Cette conception rend très simple d'interagir avec votre base de données et transmettre des variables ainsi que de faire en sorte que vos classes DonT violer la SRP

http://jdbi.org/sql_object_overview/

0

variables de passage est assez simple dans une base MySQL requête en utilisant Java.

  • Écrivez votre requête
  • et écrire la variable ""
  • Dans mon cas, je passe 'conition' et 'tablename' dynamiquement.
  • Merci beaucoup d'avoir passé une bonne journée.

    @Override publique LinkedList getNameList (condition String, String tableName, String projectName) {// TODO méthode généré automatiquement 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; 
    

    }

Questions connexes