下面是代碼
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 ...驅動程序將隨着您使用的數據庫而改變。
希望這會有所幫助。
如何在你問之前將它炸死? http://www.mkyong.com/tutorials/jdbc-tutorials/ – Reddy
可能是他不知道哪些關鍵字用於搜索(我的意思是「JDBC」) – Karloss
@Karloss,我沒有投反對票,也沒有做出任何侵略評論。這就是爲什麼我給了鏈接。 :) – Reddy