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

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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序