Jdbc:Connection 在我的程序中返回 null 怎么办?
Jdbc:Connection is returning null in my program what to do?
我收到异常 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;
}
}
不正确的class名字
如果您使用 Connector/J product as your JDBC driver,您的 class 名称似乎不正确。
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
。警告:我经常使用 Postgres & H2,而不是 MySQL,所以我可能不是最新的。
有关连接和使用 MySQL 的完整示例的源代码,请参见另一个问题的 my Answer。以下是与 DataSource
和 Connection
.
有关的部分
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();
}
这是我尝试将 java class 与 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;
}
我收到异常 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;
}
}
不正确的class名字
如果您使用 Connector/J product as your JDBC driver,您的 class 名称似乎不正确。
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
。警告:我经常使用 Postgres & H2,而不是 MySQL,所以我可能不是最新的。
有关连接和使用 MySQL 的完整示例的源代码,请参见另一个问题的 my Answer。以下是与 DataSource
和 Connection
.
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();
}
这是我尝试将 java class 与 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;
}