Java 与 Sql 服务器的连接出现 jtds 错误

Java connection to Sql server with jtds error

我使用此代码与 Sql 服务器建立连接,但出现该错误 当我使用 Class.forName(driver) 时,它连接正确,但我更喜欢使用 DataSourse。

static final BasicDataSource dataSource = new BasicDataSource();


static {
    dataSource.setDriverClassName("net.sourceforge.jtds.jdbc.Driver");
    dataSource.setUrl("jdbc:jtds:sqlserver://Mypc/Mydb;instance=SQLEXPRESS;");
    dataSource.setUsername("");
    dataSource.setPassword("");


}

public static void main(String[] args){
     try{
dataSource.getConnection();
}
     catch (SQLException ex){
        System.out.println(ex);
    }}


public static Connection getConnection() throws SQLException {
    return dataSource.getConnection();
}

我明白了

 Exception in thread "main" java.lang.AbstractMethodError
at net.sourceforge.jtds.jdbc.JtdsConnection.isValid(JtdsConnection.java:2833)
at org.apache.commons.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:918)
at org.apache.commons.dbcp2.PoolableConnection.validate(PoolableConnection.java:283)
at org.apache.commons.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:357)
at org.apache.commons.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2307)
at org.apache.commons.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2290)
at org.apache.commons.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2039)
at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)

您必须将 validationQuery="select 1" 添加到您的 dataSource

dataSource.setValidationQuery("select 1");