JDBC笔记

来源:互联网 发布:耕地质量等级数据库 编辑:程序博客网 时间:2024/05/22 22:24

1、应用程序和数据库之间的关系:

应用程序-->JDBC-->数据库Driver-->数据库

2、链接数据库步骤:

  (1).注册驱动(只做一次)

  (2).建立连接(Connection)

  (3).创建SQL语句(Statement)

  (4).执行语句

  (5).处理结果

  (6).释放资源

3、注册驱动的方式(mySql):

  1.Class.forName("com.mysql.jdbc.Driver");

  2.DriverManager.registerDriver(new com.mysql.jdbc.Driver());

  3.System.setProperty("jdbc.drivers", "com.mysql.jdbc.Drive");

  推荐使用第一种方式。因为:第2种方式会生成2个Driver对象的实例。第3种方式会对数据库驱动产生依赖。

  详细原因:http://xm-king.iteye.com/blog/798331

  三种驱动方式的详细介绍:http://blog.sina.com.cn/s/blog_670c5a4001017e2e.html

4、数据库连接URL规则

  JDBC:子协议:子名称//主机名:端口/数据库名?属性名=属性值&属性名=属性值&...

  各种数据库连接URL总结:http://blog.csdn.net/it_yijihua/article/details/17878649

5、PreparedStatement和Statement的区别

    PreparedStatement接口继承Statement,三种方法execute()、executeQuery()和executeUpdate()已被更改不再需要参数。

  (1).最重要的一点是极大地提高了安全性。防止SQL注入。

  (2).PreparedStatement,数据库会对sql语句进行预编译,第一次执行消耗较高,但重复执行效率更高(数据库连接未关闭的前提)。

  (3).PreparedStatement代码可读性和可维护性更高。

6、大文本文件(字符流)、二进制文件(字节流)的存取

  保存

// 存字符流File file1 = new File(pathname1);Reader reader = new BufferedReader(new FileReader(file1));ps.setCharacterStream(1, reader, (int) file1.length());// 存字节流File file2 = new File(pathname2);InputStream in = new BufferedInputStream(new FileInputStream(file2));ps.setBinaryStream(2, in, (int) file2.length());


  读取

//读字符流BufferedReader br = new BufferedReader(rs.getCharacterStream("content"));String str = null;StringBuffer sb = new StringBuffer();while ((str = br.readLine()) != null) {sb.append(str + "\r\n");}//读字节流InputStream in = rs.getBinaryStream("pictures");File file = new File("src/filePack/147124064892_bak.jpg");OutputStream out = new BufferedOutputStream(new FileOutputStream(file));byte[] buff = new byte[1024];for (int i = 0; (i = in.read()) > 0;) {out.write(buff, 0, i);}

字节流与字符流的区别详解:http://http://blog.csdn.net/zxman660/article/details/7875799




 

1 0
原创粉丝点击