JDBC操作数据库的基本流程

来源:互联网 发布:linux是什么那几个单词 编辑:程序博客网 时间:2024/06/02 19:45
所有的JDBC应用程序都具有下面的基本流程:
  1、加载数据库驱动并建立到数据库的连接。
  2、执行SQL语句。
  3、处理结果。
  4、从数据库断开连接释放资源。

下面我们就来仔细看一看每一个步骤:

其实按照上面所说每个阶段都可得单独拿出来写成一个独立的类方法文件。共别的应用来调用。

1、加载数据库驱动并建立到数据库的连接:

String driverName="com.mysql.jdbc.Driver";String connectiionString="jdbc:mysql://10.5.110.239:3306/test?"+"user=root&password=chen&characterEncoding=utf-8";Connection connection=null;try {Class.forName(driverName);//这里是所谓的数据库驱动的加载connection=(Connection) DriverManager.getConnection(connectiionString);//这里就是建立数据库连接System.out.println("数据库连接成功");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}return connection;
2、执行SQL语句:

在执行sql语句的时候,这里常见的有两种类型的语句对象:

Statement:它提供了直接在数据库中执行SQL语句的方法。对于那些只执行一次的查询、删除或者一种固定的sql语句来说已经足够了。

Statement statement=(Statement) dUtil.getConnection().createStatement();String sql="delete from diary where title="+"'"+title+"'";int count=statement.executeUpdate(sql);System.out.println("删除成功");

Preparedstatement:这种语句对象用于那些需要执行多次,每次仅仅是数据取值不同的SQL语句,它还提供了一些方法,以便指出语句所使用的输入参数。

String sql="insert into diary(title,content,authorname,time) values(?,?,?,now())";try {PreparedStatement preparedStatement=(PreparedStatement) dUtil.getConnection().prepareStatement(sql);String title=diary.getTitle();String content=diary.getContent();String authorname=diary.getAuthorName();preparedStatement.setString(1, title);preparedStatement.setString(2, content);preparedStatement.setString(3, authorname);
  3、处理结果:

ResultSet resultSet=statement.executeQuery(sql);while (resultSet.next()) {Diary diary=new Diary();diary.setAuthorName(resultSet.getString("authorname"));diary.setContent(resultSet.getString("content"));diary.setTitle(resultSet.getString("title"));diary.setId(resultSet.getInt("id"));Date time=resultSet.getDate("time");
此处,应该知道的是:Statement执行sql语句的方法:insert、Update、delete语句是使用了Statement的executeUpdate方法执行的,返回结果是插入、更新、删除的个数。而select语句执行较为特别是使用了Statement的executeQuery方法执行的。返回的结果存放在resultset结果集中,我们可以调用next()方法来移到结果集中的下一条记录。结果集由行和列组成,各列数据可以通过相应数据库类型的一系列get方法(如getString,getInt,getDate等等)来取得。

4、从数据库断开连接释放资源:

在结果集、语句和连接对象用完以后,我们必须正确地关闭它们。连接对象、结果集对象以及所有的语句对象都有close()方法,通过调用这个方法,我们可以确保正确释放与特定数据库系统相关的所有资源。

public static void closeConnection(ResultSet resultSet,PreparedStatement preparedStatement, Connection connection) throws SQLException {if (resultSet!=null) resultSet.close();if (preparedStatement!=null) preparedStatement.close();if(connection!=null&&connection.isClosed()==false) connection.close();System.out.println("数据库关闭");}



原创粉丝点击