日期:2014-05-16  浏览次数:20514 次

JDBC 连接步骤

所用的包都是java.sql......

1.加载驱动程序?

? ?Class.forName("com.mysql.jdbc.Driver");

2. 创建数据库连接
????String url = "jdbc:mysql://localhost:3306/olive?useUnicode=true&characterEncoding=GBK";
? ? String username = "root";
? ? String password = "1989";
? ? Connection connection = DriverManager.getConnection(url,username,password);

3.创建Statement?
????????Statement statement = connection.createStatement();(静态SQL语句)
? ? 或PreparedStatement preparedStatement = connection.prepareStatement(sql);(动态SQL语句)
? ? 或CallableStatement callableStatement = connection.prepareCall("{CALL demoSql(?,?)} ");(数据库存储过程)

4.执行SQL语句,(查询的情况下获得ResultSet)
? ? ????ResultSet resultSet = statement.executeQuery(sql);(用于查询操作,返回 ResultSet)
? ? 或 statement.executeUpdate(sql);(用于执行INSERT,UPDATE操作,返回操作数 int)
? ? 或 statement.execute(sql);(用于执行返回多个结果集,多个更新计数或二者结合返回状态 boolean);

5.处理结果
? ? *注意:获取行数: resultSet.last(); int rowCount = resultSet.getRow();
? ? ? ? ? ? ? 获取列数: int columnCount = resultSet.getMetaData().getColumnCount();
? ??
6.关闭JDBC对象
? ? 关闭顺序:记录集(ResultSet),声明(Statement),连接对象(Connection)。