Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing java string variable in mysql query

Tags:

java

sql

How to pass java string variable in sql query .I have done all the JDBC connection .

My sql database query is

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

It is not working. However if i do the following code its working

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

Now tell me how should i pass variable name to the sql query to execute this. Jst tell me how to pass the variable locationnames to comp.name.

My complete java function looks like this: locationCombo denotes item selected in combobox. CropCombo also denotes the same...

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

    }
like image 316
enjal Avatar asked Jul 09 '14 03:07

enjal


People also ask

How do I pass a string in SQL?

To pass string parameters in an SQL statement, single quotes (' ') must be part of the query. Example for Single quotes being part of the query.

Can we pass variable in SQL query?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

What is %s and %D in mysql?

12 years, 11 months ago. it's for php to know how to handle the parameters, %d – the argument is treated as an integer, and presented as a (signed) decimal number. %s – the argument is treated as and presented as a string. in your examples, $slug is a string and $this->id is an integer.

Can you use variables in mysql?

Mysql also supports the concept of User-defined variables, which allows passing of a value from one statement to another. A user-defined variable in Mysql is written as @var_name where, var_name is the name of the variable and can consist of alphanumeric characters, ., _, and $.


1 Answers

Use a PreparedStatement and bind the String parameter,

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) {
    }
  }
}

Edit (Based on your additional code, change it to something like)

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();
like image 98
Elliott Frisch Avatar answered Oct 04 '22 03:10

Elliott Frisch