RGB*_*314 5 mysql eclipse tomcat jdbc
我正在尝试编写一个程序来连接到eclipse中的MySQL数据库,但是我收到错误"java.sql.SQLException:找不到合适的驱动程序".
java代码是:
import java.sql.*;
public class FirstExample {
//static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String S_DB_URL = "jdbc:mysql://localhost:3306/emp";
static final String S_USER = "root";
static final String S_PASS = "root";
public static void main(String[] args) {
try {
System.out.println("Connecting to database...");
//Class.forName(S_JDBC_DRIVER);
Connection connection = DriverManager.getConnection(S_DB_URL,
S_USER, S_PASS);
System.out.println("Creating statement...");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM Employee";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int iId = resultSet.getInt("id");
int iAge = resultSet.getInt("age");
String sFirst = resultSet.getString("fname");
String sLast = resultSet.getString("lname");
System.out.print("ID: " + iId);
System.out.print("\tAge: " + iAge);
System.out.print("\tFirst: " + sFirst);
System.out.println("\tLast: " + sLast);
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException se) {
for (Throwable t : se) {
t.printStackTrace();
}
}
System.out.println("Goodbye!");
}
Run Code Online (Sandbox Code Playgroud)
}
控制台选项卡中的输出是:
Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/emp
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at FirstExample.main(FirstExample.java:21)
Goodbye!
Run Code Online (Sandbox Code Playgroud)
我使用过MySQL Connector/J. 它在MySQL安装目录中解压缩,并且jar文件被添加到CLASSPATH中.
另请参阅此图片.有一个 !在项目根目录标记.image01
当我包含2个注释语句时,我得到了错误,如下图所示:image02:
static final String S_JDBC_DRIVER = "com.mysql.jdbc.Driver";
Class.forName(S_JDBC_DRIVER);
Run Code Online (Sandbox Code Playgroud)
对于除了最简单的应用程序之外的所有应用程序,不CLASSPATH使用环境变量。通常,这些库包含在jar 清单的条目中,或者包含在Class-Path-cp option of the java commandline.
在这种情况下,您需要将 MySQL JDBC 驱动程序添加到 Eclipse 项目的构建路径中。
| 归档时间: |
|
| 查看次数: |
23246 次 |
| 最近记录: |