【问题标题】:Jsp/MySQL- Storing output from SELECT query into a string?Jsp/MySQL-将 SELECT 查询的输出存储到字符串中?
【发布时间】:2018-08-11 09:15:26
【问题描述】:

这是我的选择查询

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

【问题讨论】:

  • 向我们展示您编写的执行查询并遍历结果集的代码,并解释将结果存储在字符串中的哪些问题。
  • @Jim Garrison 我将代码编辑到我的原始帖子中
  • 我尝试删除“con.close()”,现在我得到了存储在表中“名字”列下的最后一个值 - 我的选择查询有问题吗?我知道我的用户名 cookie 传入了正确的值,因为我已经输出并检查了它。

标签: java mysql jsp


【解决方案1】:

查询错误,类似于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);  
}

【讨论】:

  • 谢谢!我对 MySQL 很陌生,所以我已经坚持了一段时间。
猜你喜欢
  • 2011-06-22
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-08-18
  • 2015-01-26
  • 1970-01-01
  • 2012-11-13
相关资源
最近更新 更多