jdbc操作数据库的基本流程分析
2022-11-12 09:30:24
内容摘要
这篇文章主要为大家详细介绍了jdbc操作数据库的基本流程分析,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!所有的JDBC应用程序都具有下
文章正文
这篇文章主要为大家详细介绍了jdbc操作数据库的基本流程分析,具有一定的参考价值,可以用来参考一下。
对此感兴趣的朋友,看看idc笔记做的技术笔记!
所有的JDBC应用程序都具有下面的基本流程: 1、加载数据库驱动并建立到数据库的连接。 2、执行SQL语句。 3、处理结果。 4、从数据库断开连接释放资源。下面我们就来仔细看一看每一个步骤:其实按照上面所说每个阶段都可得单独拿出来写成一个独立的类方法文件。共别的应用来调用。1、加载数据库驱动并建立到数据库的连接:代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <code>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 block e.printStackTrace(); } return connection; </code> |
代码如下:
1 2 3 4 5 6 7 8 | <code>Statement statement=(Statement) dUtil.getConnection().createStatement(); String sql= "delete from diary where title=" + "'" +title+ "'" ; int count =statement.executeUpdate(sql); System.out.println( "删除成功" ); </code> |
代码如下:
1 2 3 4 5 6 7 8 9 10 | <code>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); </code> |
代码如下:
1 2 3 4 5 6 7 8 9 | <code>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" ); </code> |
代码如下:
1 2 3 4 5 6 7 8 9 | <code> 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( "数据库关闭" ); } </code> |
注:关于jdbc操作数据库的基本流程分析的内容就先介绍到这里,更多相关文章的可以留意
代码注释