package com.bjsxt.jdbc.datesource;import java.sql.*;
import java.util.LinkedList;public class MyDataSource {
private String url = "jdbc:mysql://localhost:3306/mydata";
private String username = "root";
private String password = "880521";
private static int initCount = 5;
private static int maxCount = 10;
private int currentCount = 0;
private LinkedList<Connection> connectionsPool= new LinkedList<Connection>();

public MyDataSource() {
for(int i=0;i<10;i++) {
this.connectionsPool.addLast(this.createConn());
this.currentCount++;
}
}

public Connection getConnection() {        //有错误getConnection() 下有红线
synchronized (connectionsPool) {
if(this.connectionsPool.size() > 0)
return this.connectionsPool.removeFirst();

if(this.currentCount < maxCount) {
this.currentCount++;
return this.createConn();
}

}

}
public void free(Connection conn) {
this.connectionsPool.addLast(conn);
}
private Connection createConn() {               //有错误createConn() 下有红线
try {
 return DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
}
}

解决方案 »

  1.   

    要怎么return啊   我按着视频做的  他是对的 我有错误 郁闷啊
      

  2.   

     public Connection getConnection() {
    方法中加一个else return。语句。
    private Connection createConn() {
    在catch中也增加个return 语句,返回null也行。
      

  3.   

    return 放在if中,编译器认为是有可能执行不到的.除非if和else两个分支中都放上return .try,catch也一样道理.
      

  4.   

    你的createConn方法如果没有捕获异常,则返回一个连接。那么如果捕获了异常怎么办?返回什么?
    前面的错误和你调用这个方法有关。一种,捕获了异常,也要返回一个对象。至于是null还是什么,你自己根据需求看第二种, throw 一个异常出去。直接throw e也好或者new Exception也好。看需求。但这就要调用方能够处理异常,而且函数createConn也要标识出 throws Exception