使用java从mysql数据库读取数据

时间:2013-12-17 05:49:43

标签: java mysql sql swing netbeans-7

首先,我正在使用jTextFields阅读用户的产品名称和产品数量。对于该产品,我使用sql查询从数据库中读取产品ID和价格。但是在下面的代码中我在jtextField中显示产品价格,但在运行tha文件时,我成功执行了查询,但是我没有在jtextField中获得任何内容。

请检查sql查询和结果集使用, 表名是“item”,数据库名是“myshop”, 我全局声明变量,这段代码在jButton的'ActionPeformed'部分。

String item_name=name.getText();
int item_no=Integer.parseInt(no.getText());
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
try{       
Class.forName("com.mysql.jdbc.Driver");
Connection con(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
java.sql.Statement stmt=con.createStatement();
if (stmt.execute(sql)) {
rs = stmt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
} else {
System.err.println("select failed");}
int idIndex   = rs.findColumn("id");
int priceIndex    = rs.findColumn("price");

while(rs.next()){
item_id=rs.getInt(idIndex);
item_price=rs.getInt(priceIndex);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2  
  }
}
catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}

5 个答案:

答案 0 :(得分:3)

此行应为

String sql="SELECT id,price FROM item WHERE item.name='item_name'";
像这样

String sql="SELECT id,price FROM item WHERE item.name='"+item_name+"'";

答案 1 :(得分:3)

使用PreparedStatement,这样您就不必担心划分所有变量:

String sql="SELECT id, price FROM item WHERE item.name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, item_name);
ResultSet rs = stmt.executeQuery();

然后准备好的语句将用适当的引号替换你的变量。

答案 2 :(得分:1)

您需要将item_name作为参数并放入引号,

String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";

答案 3 :(得分:0)

使用PreparedStatement

尝试避免此类错误
String sql="SELECT id,price FROM item WHERE item.name=?";  
PreapredStatement ps = con.prepareStatement(sql);
ps.setString(1,item_name); 
ResultSet rs = ps.executeQuery(); 

还使用PreparedStatement prevent SQL injection attack.

答案 4 :(得分:0)

试试这段代码。

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
            PreparedStatement pt=con.prepareStatement("SELECT id,price FROM item WHERE item.name=?");
            pt.setString(1,"item_name");
          ResultSet rs;
           if(pt.execute())
           {
                rs=pt.getResultSet();
               JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
          }
           else {
    System.err.println("select failed");
           }

        while(rs.next()){
    item_id=rs.getInt(1);
    item_price=rs.getInt(2);
    jTextField1.setText(""+item_price);//displaying product price in a jTextField1
    jTextField2.setText(""+item_id);//displaying product id in a jTextField2    

        }
相关问题