为什么和视频代码一摸一样确报了空指针?

为什么和视频代码一摸一样确报了空指针?

package com.imooc.jdbc.demo3;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import com.imooc.jdbc.utils.JDBCUtils;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceDemo1 {
	@Test
	public void demo1() {
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try {
			ComboPooledDataSource dataSource=new ComboPooledDataSource();
			
			dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
		
		dataSource.setJdbcUrl("jdbc:mysql:///jdbctest");
		dataSource.setUser("root");
		dataSource.setPassword("abc");
		dataSource.setMaxPoolSize(20);
		dataSource.setInitialPoolSize(3);
			conn=dataSource.getConnection();
			
			String sql="select *from user";
			pstmt=conn.prepareStatement(sql);
			pstmt.executeQuery();
			while(rs.next()) {
				System.out.println(rs.getInt("uid")+"  "+rs.getString("username")+"  "+rs.getString("password")+"  "+rs.getString("name"));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtils.release(rs, pstmt, conn);
		}
	}
}

错误提示

Jan 17, 2019 10:09:44 PM com.mchange.v2.log.MLog <clinit>

信息: MLog clients using java 1.4+ standard logging.

Jan 17, 2019 10:09:44 PM com.mchange.v2.c3p0.C3P0Registry banner

信息: Initializing c3p0-0.9.1.2 [built 21-May-2007 15:04:56; debug? true; trace: 10]

Jan 17, 2019 10:09:45 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager

信息: Initializing c3p0 pool... com.mchange.v2.c3p0.ComboPooledDataSource [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, dataSourceName -> 1hge0yta0pkf91v9w9grl|123a439b, debugUnreturnedConnectionStackTraces -> false, description -> null, driverClass -> com.mysql.cj.jdbc.Driver, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge0yta0pkf91v9w9grl|123a439b, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, jdbcUrl -> jdbc:mysql:///jdbctest, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, numHelperThreads -> 3, numThreadsAwaitingCheckoutDefaultUser -> 0, preferredTestQuery -> null, properties -> {user=******, password=******}, propertyCycle -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false ]

java.lang.NullPointerException

at com.imooc.jdbc.demo3.DataSourceDemo1.demo1(DataSourceDemo1.java:35)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:498)

at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)

at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)

at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)

at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)

at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)

at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)

at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)

at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)

at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)

at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)

at org.junit.runners.ParentRunner.run(ParentRunner.java:363)

at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)

at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)

at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)


正在回答

登陆购买课程后可参与讨论,去登陆

4回答

同学要学会看报错信息哦,空指针异常,说明报错的那一样有值为null的对象去调用方法或属性,同学看一下第35行,应该是while(rs.next()) {

rs为什么是null呢?

因为同学把它初始化为null后,就直接去调用了它的方法,同学忘记把查询出来的结果赋值给rs了。

同学把查询出来的结果赋值给rs就可以了

http://img1.sycdn.imooc.com//climg/5c413463000164e707660460.jpg


如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


  • Clark_Chan 提问者 #1
    pstmt.executeQuery(); ResultSet rs2 = rs; while(rs2.next()) { System.out.println(rs2.getInt("uid")+" "+rs2.getString("username")+" "+rs2.getString("password")+" "+rs2.getString("name")); } 我这样改了还是不行,依然是空指针。
    2019-01-18 10:40:27
  • 好帮手慕阿莹 回复 提问者 Clark_Chan #2
    不是要再写一个ResultSet 呦,同学这样写ResultSet rs2 = rs也是没有意义的呢,因为rs本身就是null,再赋值给rs2,rs2也就成了null。应该是把查询的结果赋值给rs,这样while(rs.next()) 种rs就有值了。祝学习愉快。 rs=pstmt.executeQuery();
    2019-01-18 10:45:25
  • Clark_Chan 提问者 #3
    我又对着视频在打一遍还是不行,就是rs出现了问题,可是上课的视频中为什么就可以运行呢?
    2019-01-18 10:59:22
好帮手慕阿莹 2019-01-18 11:01:53

同学再看一下老师给你的回复呦:视频中老师也是把查询结果赋值给了rs的,但是同学的没有

http://img1.sycdn.imooc.com//climg/5c4141690001357508270533.jpg


如果我的回答解决了你的疑惑,请采纳!祝学习愉快!


有点麋鹿 2019-01-17 23:47:00

url=jdbc:mysql:///imooc?useSSL=false&serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf-8

有点麋鹿 2019-01-17 23:45:48

代码没有问题的话,应该是连接写错了吧!!我看你的链接不一致

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
Java数据库开发与实战应用2018版
  • 参与学习           人
  • 提交作业       277    份
  • 解答问题       4297    个

Java数据库开发的必备技能,从流行的MySQL数据库开始,到Java原生的数据库管理接口JDBC的使用,再到常用的数据持久化框架MyBatis,让你向Java工程师的目标又迈进了一步!

了解课程
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师