Jdbc:Connection 在我的程序中返回 null 怎么办?

时间:2021-06-02 20:33:41

标签: java jdbc

由于 java.sql.Connection.prepareStatement(String) 为空,我收到异常为 con,我不知道为什么,因为我已经添加了 MySQL 连接器 jar 文件。

import java.sql.Connection;
import java.sql.PreparedStatement;

public class Studentdao {

public static boolean insertStudenttoDB(Student st) {

    boolean f=false;
try {
Connection con =CP.createc();
//jdbc code
String q="insert into students(sname,sphone scity)values(?,?,?)";
PreparedStatement pstmt=con.prepareStatement(q);
pstmt.setString(1,st.getStudentname());
pstmt.setString(2,st.getStudentcity());
pstmt.setLong(3,st.getStudentphone());

//execute
pstmt.executeUpdate();
f=true;

}
catch(Exception e) {
    e.printStackTrace();
}
return f;
}
}

这是我的连接程序

import java.sql.Connection;
import java.sql.DriverManager;

public class CP {


static Connection con;
//load driver
public static Connection createc() {
    try {
Class.forName("com.sql.jdbc.Driver");

//creating connection
String user="mysql";
String password="mysql";
String url="jdbc:mysql://localhost:3306/student_manage";
    con=DriverManager.getConnection(url,user,password);
     
}catch(Exception e) {
    e.printStackTrace();
}

 return con;        
}
}

2 个答案:

答案 0 :(得分:0)

类名不正确

如果您使用 Connector/J 产品作为您的 JDBC driver,您的类名似乎不正确。

Connector/J 手册的

Section 3.6.1 显示了 "com.mysql.cj.jdbc.Driver" 的使用与 "com.sql.jdbc.Driver" 的使用。这是他们的代码示例:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Notice, do not import com.mysql.cj.jdbc.*
// or you will have problems!
public class LoadDriver {
    public static void main(String[] args) {
        try {
            // The newInstance() call is a work around for some
            // broken Java implementations
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
        } catch (Exception ex) {
            // handle the error
        }
    }
}

DataSource

请注意,现代 Java 通常不需要您使用 Class.forName。 JDBC 架构在多年前进行了改进,现在可以使用 Java Service Provider Interface (SPI) 技术自动定位和加载驱动程序。

我建议您养成使用 DataSource 获取连接的习惯,而不是调用 DriverManager。使用 DataSource 使您的代码更加灵活。您将能够切换 JDBC 驱动程序、添加连接池和外部化配置信息(服务器地址、数据库名称、用户名、密码等)以进行部署。

通常您的 JDBC 驱动程序带有 DataSource 的基本实现。查看文档,了解您可以设置的所有各种选项,特定于您的数据库(在本例中为 MySQL)。

对于 MySQL,我了解当前在 Connector/J 中提供的 DataSource 的实现是 com.mysql.cj.jdbc.MysqlDataSource。警告:我经常使用 PostgresH2,而不是 MySQL,所以我可能不是最新的。

有关连接和使用 MySQL 的完整示例的源代码,请参阅另一个问题的 my Answer。以下是与 DataSourceConnection 相关的部分。

    private DataSource configureDataSource ( )
    {
        System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );

        com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() );  // Implementation of `DataSource` bundled with H2.
        dataSource.setServerName( "db-mysql-sfo3-422-do-user-8982-1.x.db.ondigitalocean.com" );
        dataSource.setPortNumber( 24_090 );
        dataSource.setDatabaseName( "defaultdb" );
        dataSource.setUser( "scott" );
        dataSource.setPassword( "tiger" );
        return dataSource;
    }

在应用生命周期的早期,实例化并保留从该方法返回的 DataSource 对象。请记住,DataSource 仅包含配置详细信息;它本身不是开放资源,不需要关闭。

DataSource dataSource = this.configureDataSource();

要打开连接,请将 DataSource 传递给您想要连接到数据库的方法。

private void dumpTable ( DataSource dataSource ) { … }

这是 dumpTable 方法的一部分。

注意 try-with-resources 语法的使用会按照它们声明的顺序自动关闭打开的资源,即使在失败并抛出异常的情况下也是如此。

        String sql = "SELECT * FROM event_ ;";
        try (
                Connection conn = dataSource.getConnection() ;  // ? Use the passed `DataSource` object to ask for a `Connection` object.
                Statement stmt = conn.createStatement() ;
                ResultSet rs = stmt.executeQuery( sql ) ;
        )
        {
            …
        }
        catch ( SQLException e )
        {
            e.printStackTrace();
        }

答案 1 :(得分:0)

这是我尝试将 java 类与 mysql 连接的代码。确保您必须将所需的驱动程序添加到您的库中。

import java.sql.Connection;
import java.sql.DriverManager;
public class Server {
public static Connection getConnection()
{
try
{
   Class.forName("com.mysql.jdbc.Driver");
   String urls = "127.0.0.1";//you can even replace this with localhost
   String username = "yourusername";
   String password = "1234";
   Connection conn = DriverManager.getConnection("jdbc:mysql://"+urls+":3306/yourdb?useUnicode=yes&characterEncoding=UTF-8", username, password);
   return conn;
}
catch(Exception e)
{
   e.printStackTrace();
}
return null;
}