public class jdbctest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
int i=0;
try {
// Class.forName("com.mysql.cj.jdbc.Driver");注释,因为可以自动加载
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?" +
"user=root&password=richtev&serverTimezone=UTC");
//不需要Classforname自动加载合适驱动
stmt = conn.createStatement();
String sql = "insert into user (name,age)values('kkk',18)";
i = stmt.executeUpdate(sql);
if(i>0){
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
UtilJDBC.close(conn,stmt,rs);
}
}
}
上面代码正常运行,成功插入数据库
但是使用servlet,间接调用下面添加时候
public class studentService {
//student数据访问类
public int addStudent(Student stu){
Connection conn = null;
PreparedStatement ps = null;
ResultSet re = null;
System.out.println(stu.getName());
System.out.println(stu.getAge());
int i=-1;
//注册,连接,
try {
//这行代码就会出错,完全复制过来的
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?" +
"user=root&password=richtev&serverTimezone=UTC");
//这行代码就会出错,完全复制过来的
String sql = "insert into user (name,age) values(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1,stu.getName());
ps.setInt(2,stu.getAge());
i = ps.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
UtilJDBC.close(conn,ps,re);
}
return i;
}
}
使用是idea。会出现
No suitable driver found for jdbc:mysql://localhost:3306/student?user=root&password=123123&serverTimezone=UTC
明明已经可以单独插入数据了,为什么使用servlet时候回报错呢?
相似问题