我现在已经尝试了几个小时,但没有成功。我下载了JDBC驱动程序,它显示它是我在Eclipse的Package Explorer下引用的库之一,但每次我尝试运行我的代码时都会出错。我的数据库很好,因为我可以更改它并从MySQL命令行客户端查看它。
我实际上按照指南说明如何操作,只是将数据库中的信息替换为我的信息。
import java.sql.*;
public class FirstExample {
//JDBC Driver Name and Database URL
final static String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final static String DB_URL = "jdbc:mysql://localhost/test_database";
//Database Credentials
static final String USER = "user_one";
static final String PASS = "User_one_password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//Register JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
//Open a Connection
System.out.println("Connecting to the Database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//Execute a Query
System.out.println("Creating Statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT * FROM user";
ResultSet rs = stmt.executeQuery(sql);
//Extract Data from Result Set
while (rs.next()) {
//Retrieve by Column Name
int id = rs.getInt("id");
String first = rs.getString("name");
//Display Values
System.out.print("ID: " + id);
System.out.println("Name: " + first);
}
//Clean Up Environment
rs.close();
stmt.close();
conn.close();
} catch (SQLException se) {
//Handle Errors For JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle Errors for Class.forName
e.printStackTrace();
} finally {
//Finally Block used to close resources
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
//Nothing We Can Do
}
try {
if (conn != null)
conn.close();
} catch (Exception se) {
se.printStackTrace();
}//End Finally Try
}//End Try
System.out.println("Goodbye!");
}//End Main
}//End First Example
这是我得到的错误http://pastebin.com/hLSxV3aq