当前位置:Gxlcms > 数据库问题 > 解决Tomcatt下连接数据库的classNoFount问题

解决Tomcatt下连接数据库的classNoFount问题

时间:2021-07-01 10:21:17 帮助过:30人阅读

public class SQLtest { // JDBC 驱动名及数据库 URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&" + "characterEncoding=utf-8&useSSL=true&serverTimezone=GMT%2B8"; // 数据库的用户名与密码,需要根据自己的设置 static final String USER = "root"; static final String PASS = "123456"; public boolean mySql(String sname, String spassword) { // public static void main(String[] args) { // String sname = "user1"; // String spassword="123456"; Boolean success = false; Connection conn = null; Statement stmt = null; try { // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); // 执行查询 System.out.println(" 实例化Statement对象..."); stmt = conn.createStatement(); String sql; sql = "SELECT name,password FROM table_name "; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while (rs.next()) { // 通过字段检索 String name = rs.getString("name"); String password = rs.getString("password"); // // 输出数据 // System.out.println("用户名: " + name); // System.out.println("密码: " + password); if (name.equals(sname) && password.equals(spassword)) { success = true; } } // 完成后关闭 rs.close(); stmt.close(); conn.close(); } catch (SQLException se) { // 处理 JDBC 错误 se.printStackTrace(); } catch (Exception e) { // 处理 Class.forName 错误 e.printStackTrace(); } finally { // 关闭资源 try { if (stmt != null) stmt.close(); } catch (SQLException se2) { }// 什么都不做 try { if (conn != null) conn.close(); } catch (SQLException se) { se.printStackTrace(); } } System.out.println("Goodbye!"); System.out.println(success); return success; } }

然后在Tomcat中时则出现java.lang.ClassNotFoundException: com.mysql.jdbc.Driver,数据库驱动不能找到的问题。.jar包已经成功导入,

在java项目中,只需要引入mysql-connector-java-5.1.7-bin.jar就可以运行java项目。

但是在web项目中,当Class.forName("om.mysql.jdbc.Driver")时;是不会去查找字符串,不会去查找驱动的。所以只需要把mysql-connector-java-5.1.7-bin.jar拷贝到tomcat下lib目录就可以了。



解决Tomcatt下连接数据库的classNoFount问题

标签:驱动   cut   als   print   mysq   out   user   from   ...   

人气教程排行