关于preparestatement行 报java.lang.NullPointerException

来源:互联网 发布:ug螺纹铣刀编程 编辑:程序博客网 时间:2024/05/21 13:21

今天练习做jdbc利用工具类完成curd操作的这么个东西,在测试执行的时候一直报java.lang.NullPointerException

工具类是这样的

public class jdbcutils {public static Connection getConnection() throws Exception{Class.forName("com.mysql.jdbc.Driver");Connection connection=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3307/apartment","root","111222");return null;}public static void closeResource(Connection connection,PreparedStatement statement,ResultSet tResultSet){clostResultset(tResultSet);cloststatement(statement);closeConn(connection);}public static void closeConn(Connection conn) {if(conn!=null){try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}conn=null;}}public static void cloststatement(PreparedStatement statement){if(statement!=null){try {statement.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}statement=null;}}public static void clostResultset(ResultSet resultSet){if(resultSet!=null){try {resultSet.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}resultSet=null;}}}


测试代码是这样的


@Testpublic void run2() throws Exception{Connection connection=null;ResultSet resultSet=null;PreparedStatement statement=null;//PreparedStatement statemen;try {connection=jdbcutils.getConnection();//System.out.println(connection);String sqlString="insert into apartment values(?,?,?,?)";statement=connection.prepareStatement(sqlString);statement.setInt(1, 11);statement.setString(2, "外联部");statement.setString(3, "详情");statement.setString(4, "0");int i=statement.executeUpdate();if(i==1){System.out.println("执行成功");}else {System.out.println("失败");}} catch (Exception e) {e.printStackTrace();}finally{jdbcutils.closeResource(connection, statement, resultSet);}}}

百思不得其解,各种百度


其中有个方法是说 出现这种报错是因为mysql的服务还没开,于是去检查了一下服务,状态是正在运行,排除


还有的虽然报错和我的一样,但是代码都有所不同,因此他们代码里面的错误在我这边也并没有出现

搜了挺久的 后面看到一个回复说 可以打印报错行前面,看看是否为空,于是我打印了connection ,果然是空的,所以其实问题出在connection这里。就觉得可能是工具类的问题。

去看了工具类,才发现,getconnection方法返回的居然是null,是编写代码的时候为了开始不报错,就先设置为空,但是后面又忘了改过来了 。为自己的忘性感到十分地忧伤。




0 0
原创粉丝点击