MYSQL数据库jdbc操作数据库的基本流程详解
发布时间:2020-12-12 02:56:49 所属栏目:MySql教程 来源:网络整理
导读:《MYSQL数据库jdbc操作数据库的基本流程详解》要点: 本文介绍了MYSQL数据库jdbc操作数据库的基本流程详解,希望对您有用。如果有疑问,可以联系我们。 所有的JDBC应用程序都具有下面的基本流程: 1、加载数据库驱动并建立到数据库的连接. 2、执行SQL语句. 3
《MYSQL数据库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 block ???e.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("数据库封闭"); ?} 《MYSQL数据库jdbc操作数据库的基本流程详解》是否对您有启发,欢迎查看更多与《MYSQL数据库jdbc操作数据库的基本流程详解》相关教程,学精学透。编程之家PHP学院为您提供精彩教程。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |