栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Eclipse使用jdbc连接mysql返回null值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Eclipse使用jdbc连接mysql返回null值

在学习javaweb和servlet写一个项目时出现了空指针异常。经过异常艰难的排查后,发现虽然jdbc连接上了mysql,但是conn返回是null。后来发现应该是jdbc连接方法与jdk、mysql等的版本有关系。

1、我的jdk是1.8,因此compliance要改成对应的(之前我的是1.5,也不知道怎么搞的)。

2、我的mysql是5.5.3,版本较低。因此使用以下连接方式不可行。

 static {
		try {
			Class.forName("com.mysql.jdbc.Driver");    //反射加载
		} catch (ClassNotFoundException e) {
			System.out.println("mysql初始化失败");
			e.printStackTrace();
		}
		
	}
	
	//获取链接
	public static Connection getConn() {
		Connection conn = null;    //声明接口
		try {
			//加载驱动 库
			DriverManager.getConnection("jdbc:mysql://localhost:3306/db?user=root&password=root");
			System.out.println("success");
		} catch (SQLException e) {
			
			// TODO Auto-generated catch block
			System.out.println("连接失败");
			e.printStackTrace();
		}
		return conn;
		
	}

因此需要使用以下方式(我认为其中代码有些冗余,但是具体不太了解)

public static Connection getConn() {
		Connection conn = null;    //声明接口

			String driver = "com.mysql.jdbc.Driver";
			String url = "jdbc:mysql://localhost:3306/ebuys";
			String user = "root";
			String password = "root";
			 try {
				Class.forName(driver);
				 try {
					conn = DriverManager.getConnection(url,user,password);
				} catch (SQLException e) {
					
					e.printStackTrace();
				}
			} catch (ClassNotFoundException e) {
			
				System.out.println("连接失败");
				e.printStackTrace();
			}      
			 finally {
				
			 }
		return conn;
		
	}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/425589.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号