这是代码
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection connection = null;
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/testDb", "userName", "Password");
} catch (SQLException e) {
for(Throwable ex : e) {
System.err.println("Error occurred " + ex);
}
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connected to database!");
} else {
System.out.println("Failed to make connection!");
}
try {
Statement stmt = connection.createStatement();
String query = "select * from person ;";
//person is the table name
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getObject(1).toString();
String gender = rs.getObject(2).toString();
System.out.println("Name of the person is " + name + " and his gender is " + gender);
//Person table has name and gender column
}
} catch (SQLException e) {
e.printStackTrace();
for(Throwable ex : e) {
System.err.println("Error occurred " + ex);
}
System.out.println("Error in fetching data");
}
注意:我使用JDBC 4
的是自带的Java 7
,因此不需要明确提供驱动程序。编译器会自动从类路径中获取它。您可以下载 MySqlConnector.jar 并将其放在您的类路径中。如果您不使用 java 7,则必须使用Class.forName()
. 当然,我使用的是 MySql ......驱动程序将随着您使用的数据库而改变。
希望这可以帮助。