JDBC 操作数据库的开发步骤
来源:互联网 发布:java 伪静态化 编辑:程序博客网 时间:2024/06/04 19:34
1、加载数据库驱动并建立到数据库的连接:
try{ //加载MySql的驱动类 Class.forName("com.mysql.jdbc.Driver") ; }catch(ClassNotFoundException e){ System.out.println("找不到驱动程序类 ,加载驱动失败!"); e.printStackTrace() ; } String url = "jdbc:mysql://localhost:3306/test" ; String username = "root" ; String password = "123456" ; try{ Connection con = DriverManager.getConnection(url , username , password ) ; }catch(SQLException se){ System.out.println("数据库连接失败!"); se.printStackTrace() ; }
2、执行SQL语句:
1>PreparedStatement用于处理动态SQL语句,在执行前会有一个预编译过程,这个过程是有时间开销的,虽然相对数据库的操作,该时间开销可以忽略不计,但是PreparedStatement的预编译结果会被缓存,下次执行相同的预编译语句时,就不需要编译,只要将参数直接传入编译过的语句执行代码中就会得到执行,所以,对于批量处理可以大大提高效率。2>Statement每次都会执行SQL语句,相关数据库都要执行SQL语句的编译。3>作为开发者,应该尽可能以PreparedStatement代替Statement
Statement statement=(Statement) dUtil.getConnection().createStatement(); String sql="delete from diary where title="+"'"+title+"'"; int count=statement.executeUpdate(sql); System.out.println("删除成功"); 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); }catch(Exception se){ se.printStackTrace() ; }
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"); }
4、从数据库断开连接释放资源:
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("数据库关闭"); }
0 0
- JDBC 操作数据库的开发步骤
- JDBC操作数据库的步骤
- JDBC操作数据库的步骤
- JDBC操作数据库的步骤
- jdbc操作数据库的步骤
- JDBC操作数据库的步骤
- JDBC操作数据库的步骤
- 原生Jdbc操作Mysql数据库开发步骤
- JDBC 操作数据库步骤
- JDBC操作数据库的几个步骤
- JDBC操作数据库的编程步骤
- JDBC操作SQL Server数据库的步骤
- JDBC操作数据库的基本步骤
- JDBC操作数据库的编程步骤
- JDBC操作数据库的基本步骤
- JDBC操作数据库的基本步骤
- JDBC访问数据库的典型操作步骤
- JDBC及操作数据库步骤
- 函数realpath/mktemp/access/stat以及fsutils工具中的代码例子
- jvm内存调优关键参数-续
- Mysql联合查询UNION和UNION ALL的使用介绍
- jquery实现图片轮播图效果
- 左滑删除
- JDBC 操作数据库的开发步骤
- BNN & Dual Learning论文下载地址
- 《机器学习实战》第五章:Logistic回归(2)随机梯度上升和一个实例
- js数组赋值
- java.util.regex 正则表达式
- 32 64 peb结构体
- 传多个参数
- MVC EF 并发处理
- 由于mysql数据库服务问题引起的eclipse中的Tomcat无法启动解决方法