Jsp / MySQL-将SELECT查询的输出存储到字符串中?

时间:2018-03-03 06:13:45

标签: java mysql jsp

这是我的选择查询

("SELECT firstName FROM user WHERE username = username;")

如何将其存储到字符串变量中,以便我可以在jsp页面上输出它?

编辑:我跑的代码

string firstname;

try{  


Class.forName("com.mysql.jdbc.Driver");  

Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/contacts","root","root"); 


Statement stmt=con.createStatement();  

ResultSet rs=stmt.executeQuery("SELECT firstName FROM user WHERE username = username;");



while(rs.next())  {
fname=new String(rs.getString(1));
System.out.println("First Name:"+firstname);  
con.close();  
   }
}
catch(Exception e){ 
  System.out.println(e);
 }  

1 个答案:

答案 0 :(得分:0)

查询错误,与SELECT firstName FROM user类似。您需要将userName设置为参数。

PreparedStatement stmt=con.prepareStatement("SELECT firstName FROM user WHERE username = ?;");  
stmt.setString(1, userName);

ResultSet rs=stmt.executeQuery();

if(rs.next())  {
    fname=new String(rs.getString(1));
    System.out.println("First Name:"+firstname);  
}