Java:为什么resultser.next() ==false?我的数据库里有数据

临江御风 2018-03-22 01:45:27
代码:
import java.lang.String;
import java.sql.*;
//import java.util.Properties;
public class Jdbctext1 {
public static void main(String[] args)throws SQLException
{
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try
{
Class.forName("com.mysql.jdbc.Driver");//驱动
System.out.println("loading success!");

String url = "jdbc:mysql://localhost:3306/Library?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String user = "root";
String passward = "123456";

conn =DriverManager.getConnection(url,user,passward);//connection对象

String sql = "select * from users";
stmt = conn.prepareStatement(sql);//statement对象
rs = stmt.executeQuery();
System.out.println("id | name | passward | email | birthday");

if(rs.next()==false)System.out.println("false!");//re.next()一直等于false

while(rs.next())//进不去该循环
{
System.out.println("test");
int id = rs.getInt("id");
String name =rs.getString("name");
String psw =rs.getString("passward");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id + "|"+ name + "|" + psw+ "|" +email + "|" +birthday);
}

/******************** 下面不重要 *************************************/

System.out.println("connecting success!");
}catch(Exception e)
{
System.out.println("123");
e.printStackTrace();
}finally {

if(rs!=null) {
try
{
rs.close();
}catch(SQLException e)
{
e.printStackTrace();
}
rs=null;
}
if(stmt!=null) {
try
{
stmt.close();
}catch(SQLException e)
{
e.printStackTrace();
}
stmt=null;
}
if(conn!=null) {
try
{
conn.close();
}catch(SQLException e)
{
e.printStackTrace();
}
conn=null;
}

}

}

}
JAR

console:
...全文
630 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
仓井NULL 2018-03-23
  • 打赏
  • 举报
回复
url,user,passward 这三个能不能确定是正确的 本地的MySql能确定有数据吗
  • 打赏
  • 举报
回复
不好意思,我刚没看全代码。上面回答的不对 你可以先把sql放到你本地Navicat 中跑一下看看 是否有结果
  • 打赏
  • 举报
回复
如果你的sql只查询出来一行数据,肯定是进不去的,因为你在while之前 已经消费掉了这条数据了。 rs.next()不只是判断是否有下条数据,还有移动游标的作用。 当你只有一条数据的时候,你先rs.next();此时返回true,并且可以通过 rs.getString(index)获取数据,但是你接下来又while了,此时就把游标移动到了第二行,没有数据,返回false
空气中我最帅 2018-03-22
  • 打赏
  • 举报
回复
数据库贴出来
  • 打赏
  • 举报
回复
String sql = "select * from users;";改成这样试试看,mysql需要加分号结束吧。别的看不出有什么问题。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧