日期:2014-05-16 浏览次数:20691 次
?
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestJDBC { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost/mydata?user=root&password=root"; String sql = "select * from dept"; try { Class.forName(driver); conn = DriverManager.getConnection(url, "root", "root"); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { System.out.println(rs.getString("deptno")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } finally { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } } }
?