由于con
为null,我得到了一个异常java.sql.Connection.prepareStatement(String)
,我不知道为什么,因为我已经添加了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;
}
}
类名不正确
如果您使用Connector/J产品作为JDBC驱动程序,那么您的类名似乎不正确。
连接器/J手册的第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服务提供程序接口(SPI(技术自动定位和加载驱动程序。
我建议您养成使用DataSource
获取连接的习惯,而不是调用DriverManager
。使用DataSource
使代码更加灵活。您将能够切换JDBC驱动程序,添加连接池,并为部署外部化配置信息(服务器地址、数据库名称、用户名、密码等(。
通常JDBC驱动程序附带DataSource
的基本实现。查看文档,了解您可以设置的所有不同选项,具体针对您的数据库(本例中为MySQL(。
对于MySQL,我理解Connector/J中当前提供的DataSource
的实现是com.mysql.cj.jdbc.MysqlDataSource
。注意:我经常使用Postgres&H2,而不是MySQL。所以我可能不是最新的。
请参阅我对另一个问题的回答,了解连接和使用MySQL的完整示例的源代码。以下是与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类与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;
}