`
henry_huangs
  • 浏览: 32130 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

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)。
0
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics