使用预准备语句的SELECT查询和从用户

时间:2016-03-29 10:34:44

标签: java jdbc

我想使用用户输入的值从数据库中检索数据。值存储在名为uid的数组中。代码正在编译但不打印结果。

public static void main(String[] args) {

Connection conn = null;

PreparedStatement stmt = null;
ResultSet rs=null;
try{
  Class.forName("com.mysql.jdbc.Driver");
  conn = DriverManager.getConnection(DB_URL,USER,PASS);
  String sql1="SELECT * FROM user_ratings WHERE user_id = ?";
  stmt = conn.prepareStatement(sql1);
    for (int i:uid)
  {
     stmt.clearParameters();
   stmt.setInt(1,uid[i]);

   rs=stmt.executeQuery();
  while(rs.next())
  {
     int id  = rs.getInt("user_id");
     int mid = rs.getInt("movie_id");
     int first = rs.getInt("movie_rating");
     int second = rs.getInt("acting");
     int third = rs.getInt("visuals");
     System.out.print("User ID: " +id);
     System.out.print(", Movie ID: " +mid);
     System.out.print(", First: " +first);
     System.out.println(", Second: " +second);
     System.out.println(", Third:" +third);
  }
  }
  }

1 个答案:

答案 0 :(得分:3)

您的陈述stmt.setInt(1,uid[i]);肯定应该是stmt.setInt(1,i);

由于使用uid,您已经在迭代?i数组,并且for (int i:uid)依次提供每个值。