Whisky_F 2019-09-10 13:56 采纳率: 0%
浏览 1400

state = conn.createStatement();空指针错误?

utils代码如下:
public class Utils
{
public static String db_url="jdbc:mysql://localhost:3306/bookstoredatabase?serverTimezone=UTC&characterEncoding=utf-8";
public static String db_user="root";//数据库的用户
public static String db_password="1234";//数据库的密
public static Connection getConn()
{
Connection conn = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(db_url,db_user,db_password);
}
catch(Exception e)
{
e.printStackTrace();
}
return conn;
}
public static void close(Statement state,Connection conn)//关闭函数
{
if(state!=null)//只有状态和连接时,先关闭状态
{
try
{
((Connection) state).close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
if(conn!=null)
{
try
{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
public static void close(ResultSet rs,java.sql.Statement state,Connection conn)
{
if(rs!=null)//有结果集,状态和连接时,先关闭结果集,在关闭状态,在关闭连接
{
try
{
rs.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
if(state!=null)
{
try
{
((Connection) state).close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
if(conn!=null)
{
try
{
conn.close();
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
}
userdao代码如下:
public int login(String username,String password)
{
Connection conn = Utils.getConn();
java.sql.Statement state =null;
ResultSet rs = null;
int flag=0;
try
{
String sql1 = "select * from admin where username = admin";
state = conn.createStatement();
rs=((java.sql.Statement) state).executeQuery(sql1);
if(rs.next())
{
if(rs.getString("password").equals(password))
{
flag=1;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
Utils.close(rs, state, conn);
}
return flag;
}}
他总是显示空指针异常 是因为数据库没有连接成功 导致他是默认的null的原因吗 但是数据库连接的端口名字密码什么都是对的

  • 写回答

3条回答 默认 最新

  • 关注

    debug了吗?是不是没get到conn,debug一下就知道了

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog