import java.sql.*;
public class FirstConnection {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/*
* try { new com.mysql.jdbc.Driver(); } catch (SQLException e) {
* e.printStackTrace(); }
*/
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = DriverManager
.getConnection("jdbc:mysql://localhost/myfirstdb?user=root&password=2490248");
stmt = con.createStatement();
rs = stmt.executeQuery("select * from dept");
while (rs.next()) {
System.out.println(rs.getString("did"));
System.out.println(rs.getString("dname"));
}
} catch (SQLException e) {
System.out.println("出错了!");
e.printStackTrace();
} catch (Exception e) {
System.out.println("大问题!");
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
转载于:https://my.oschina.net/csmw00/blog/674011