当前位置: 首页 > 面试题库 >

在mysql查询中传递java字符串变量

霍修筠
2023-03-14
问题内容

如何在sql查询中传递java字符串变量。我已经完成了所有JDBC连接。

我的SQL数据库查询是

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

它不起作用。但是,如果我执行以下代码,其工作原理

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

现在告诉我如何将变量名传递给sql查询以执行此操作。Jst告诉我如何将变量locationnames传递给comp.name。

我完整的Java函数如下所示:locationCombo表示在组合框中选择的项目。CropCombo也表示相同的…

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

    }

问题答案:

使用PreparedStatement并绑定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) {
    }
  }
}

编辑 (根据您的其他代码,将其更改为类似内容)

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


 类似资料:
  • 问题内容: 我正在尝试在“ ABCXYZ123”位置更新“ hi”。但不粘贴“ hi”,而是粘贴“ Marsha”。 问题答案: 尝试:

  • 问题内容: 是否存在通过查询字符串传递数组的标准方法? 需要明确的是,我有一个带有多个值的查询字符串,其中一个是数组值。我希望将该查询字符串值视为一个数组-我不希望该数组爆炸,以使其与其他查询字符串变量没有区别。 编辑: 根据@Alex的答案,没有标准的方法可以执行此操作,因此我的后续工作是什么才是 识别 我正在读取的参数同时是 PHP 和 Javascript 数组的简单方法? 用相同的名称命名

  • 问题内容: 我正在使用AngularJS路由,并试图查看如何使用查询字符串(例如 )。Angular无法理解包含相同名称的键值对的路由: 问题答案: 我认为路由不适用于查询字符串。可以使用 如下方式而不是使用更RESTful的URL,然后按以下方式定义路由: 或许

  • 我试图通过C#代码传递此字符串,但失败了: soap:body1479374 System.xml.XmlDocument文档=新建System.xml.XmlDocument();Doc.LoadXML(字符串); 尝试发送作为整体和作为3个部分,但在A节内失败 string Sectiona=@“ soap:body ”; 字符串段B=“1479374”; 字符串节C=“”; 字符串数据=段A

  • 我需要传递一个字符串参数作为querystring参数,这应该是可选的。 在这里,我希望将位置作为可选参数。我试着用作为。但它对我不起作用。让我知道解决方案。

  • 我试图弄清楚为什么我的查询没有运行,如果运行了;为什么它不返回任何信息。我在wordpress multisite上运行这个查询是基于一个插入,通过所有网络站点并检索主站点中的所有帖子,这部分工作很好。我创建了一些代码,将两个变量合并为一个变量,以创建一个表名,如果我回显该变量,它将正确显示表名,但当我在查询中插入相同的变量时,注意到甚至会发生表已经存在于DB中的情况。代码如下: 提前道谢。