日期:2014-05-16 浏览次数:20405 次
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class Testjdbc { public static Connection getConnectionByJDBC() { Connection conn = null; try { // 装载驱动类 Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("装载驱动异常!"); e.printStackTrace(); } try { // 建立JDBC连接 conn = DriverManager.getConnection( "jdbc:mysql://192.168.3.143:3306/zzh", "zzh", "zzh"); } catch (SQLException e) { System.out.println("链接数据库异常!"); e.printStackTrace(); } return conn; } } import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestDAO { Connection conn = Testjdbc.getConnection(); String sqlx = "select code,name from test where id="; public String query(int id) { String code = ""; String name = ""; try { // 创建一个JDBC声明 Statement stmt = conn.createStatement(); // 执行查询 ResultSet rs = stmt.executeQuery(sqlx + id); while (rs.next()) { code = rs.getString("code"); name = rs.getString("name"); System.out.println(code + name); } } catch (SQLException e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { // 预防性关闭连接(避免异常发生时在try语句块关闭连接没有执行) try { if (conn != null) conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } return code + name; } }