我正在学习java,我用netbeans添加了mysql连接器,我试图做一个示例应用程序来查询数据库,但是我不知道如何调用从主方法建立连接的方法。
这是我的代码:
MySqlJdbcTest.java:
public class MySqlJdbcTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
//conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?user=root&password=");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM java");
while (rs.next()) {
String id = rs.getString("id");
String firstName = rs.getString("name");
String lastName = rs.getString("number");
System.out.println("ID: " + id + ", First Name: " + firstName
+ ", Last Name: " + lastName);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
这是 test.java 文件:
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MySqlJdbcTest prueba = new MySqlJdbcTest();
prueba();
}
}