call method for mysql connection from main in java
im learning java, i added the mysql connector with netbeans and im trying
to do a sample app to query a database, however i dont know how to call
the method that makes the connection from the main method.
here is my code:
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(); }
}
}
}
and here is the test.java file:
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MySqlJdbcTest prueba = new MySqlJdbcTest();
prueba();
}
}
No comments:
Post a Comment