适用于不同的数据库
//读取配置文件(属性文件)工具类
1 package com.pb.news.util; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Properties; 6 7 public class ConfigManager { 8 private static ConfigManager conf; 9 //properties.load(InputStream)读属性文件 10 private static Properties pro; 11 //私有化构造方法 12 private ConfigManager(){ 13 String configFile="database.properties"; 14 pro=new Properties(); 15 InputStream in=ConfigManager.class.getClassLoader().getResourceAsStream(configFile); 16 17 try { 18 pro.load(in); 19 in.close(); 20 } catch (IOException e) { 21 // TODO Auto-generated catch block 22 e.printStackTrace(); 23 } 24 25 } 26 27 public static ConfigManager getInstance(){ 28 if(conf==null ){ 29 conf=new ConfigManager(); 30 } 31 return conf; 32 } 33 //根据属性文件的key获取vaule 34 public String getString(String key){ 35 return pro.getProperty(key); 36 } 37 38 }
1 package com.pb.news.dao; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 import java.sql.Timestamp; 9 import java.util.Date; 10 11 import com.pb.news.util.ConfigManager; 12 13 //查询新闻 14 public class NewsDao { 15 // 1.Class.forName()加载驱动 16 17 public void getNewstitle() { 18 ResultSet rs = null; 19 PreparedStatement pstmt = null; 20 Connection con = null; 21 String driver = ConfigManager.getInstance().getString("jdbc.driver"); 22 String url = ConfigManager.getInstance().getString("jdbc.url"); 23 String username = ConfigManager.getInstance() 24 .getString("jdbc.username"); 25 String password = ConfigManager.getInstance() 26 .getString("jdbc.password"); 27 try { 28 29 // Class.forName("oracle.jdbc.driver.OracleDriver"); 30 Class.forName(driver); 31 // 2.DriverManager.getConnect(URL,用户名,密码)获得数据库连接(connection) 32 33 // String url = "jdbc:oracle:thin:localhost:1512:Orcl"; 34 // con = DriverManager.getConnection(url, "yaya", "whj401"); 35 con = DriverManager.getConnection(url, username, password); 36 // 查询 37 String sql = "SELECT * FROM news_detail"; 38 pstmt = con.prepareStatement(sql); 39 rs = pstmt.executeQuery(sql); 40 // 4.处理结果集 41 while (rs.next()) { 42 int id = rs.getInt("id"); 43 String title = rs.getString("title"); 44 String summary = rs.getString("summary"); 45 String content = rs.getString("content"); 46 String author = rs.getString("author"); 47 Timestamp time = rs.getTimestamp("createdate"); 48 System.out.println(id + " " + title + " " + summary + " " 49 + content + " " + author + " " + time); 50 } 51 } catch (ClassNotFoundException e) { 52 // TODO Auto-generated catch block 53 e.printStackTrace(); 54 } catch (SQLException e) { 55 // TODO Auto-generated catch block 56 e.printStackTrace(); 57 } finally { 58 try { 59 rs.close(); 60 } catch (SQLException e1) { 61 // TODO Auto-generated catch block 62 e1.printStackTrace(); 63 } 64 65 try { 66 pstmt.close(); 67 } catch (SQLException e1) { 68 // TODO Auto-generated catch block 69 e1.printStackTrace(); 70 } 71 72 try { 73 con.close(); 74 } catch (SQLException e) { 75 // TODO Auto-generated catch block 76 e.printStackTrace(); 77 } 78 79 } 80 81 } 82 83 // 插入新闻 84 85 public void add(int id, int categoryid, String title, String summary, 86 String content, String author, Date createdate) { 87 88 PreparedStatement pstmt = null; 89 Connection con = null; 90 String driver = ConfigManager.getInstance().getString("jdbc.driver"); 91 String url = ConfigManager.getInstance().getString("jdbc.url"); 92 String username = ConfigManager.getInstance() 93 .getString("jdbc.username"); 94 String password = ConfigManager.getInstance() 95 .getString("jdbc.password"); 96 try { 97 98 // Class.forName("oracle.jdbc.driver.OracleDriver"); 99 Class.forName(driver); 100 // 2.DriverManager.getConnect(URL,用户名,密码)获得数据库连接(connection) 101 102 // String url = "jdbc:oracle:thin:localhost:1512:Orcl"; 103 // con = DriverManager.getConnection(url, "yaya", "whj401"); 104 con = DriverManager.getConnection(url, username, password); 105 /* 106 * //查询 String sql = "SELECT * FROM news_detail"; pstmt = 107 * con.createStatement(); rs = stmt.executeQuery(sql); 108 */ 109 // 插入 110 String sql = "INSERT INTO NEWS_DETAIL (id,categoryId,title,summary,content,author,createdate)VALUES(?,?,?,?,?,?,?)"; 111 pstmt = con.prepareStatement(sql); 112 // 1,2,3,4,5代表哪个问号 113 pstmt.setInt(1, id); 114 pstmt.setInt(2, categoryid); 115 pstmt.setString(3, title); 116 pstmt.setString(4, summary); 117 pstmt.setString(5,content); 118 pstmt.setString(6, author); 119 pstmt.setTimestamp(7,new java.sql.Timestamp(createdate.getTime())); 120 int i = pstmt.executeUpdate();//**括号里不能放参数否则报错 121 // 4.处理结果集 122 if (i > 0) { 123 124 System.out.println("新闻插入成功"); 125 } 126 127 } catch (ClassNotFoundException e) { 128 // TODO Auto-generated catch block 129 e.printStackTrace(); 130 } catch (SQLException e) { 131 // TODO Auto-generated catch block 132 e.printStackTrace(); 133 } finally { 134 try { 135 pstmt.close(); 136 } catch (SQLException e1) { 137 // TODO Auto-generated catch block 138 e1.printStackTrace(); 139 } 140 141 try { 142 con.close(); 143 } catch (SQLException e) { 144 // TODO Auto-generated catch block 145 e.printStackTrace(); 146 } 147 148 } 149 150 } 151 152 public static void main(String[] args) { 153 NewsDao n = new NewsDao(); 154 n.add(2, 2, "尼日利亚有东方斯卡", "阿萨弗拉基第三方i阿胶", "死了一把", "ejfksa", new Date()); 155 156 } 157 158 }
PreparedStatement 对象
PreparedStatement 接口继承自Statement接口 ,PreparedStatement对象比普通的Statement对象使用起来更灵活更有效率。
PreparedStatement 事例包含已编译的SQL语句,SQL语句有一个或多个输入参数,这些参数的值在SQL语句创建时未被指定,而是为每一个参数留一个(“?”)作为占位符。
在执行PreparedStatement 对象前,必须设置每个输入参数的值,可以通过调用setXxxx()方法来完成,其中Xxxx是给参数相对应的类型。setXxxx()方法第一个参数是设置参数的序数位置第二个参数是设置给该参数的值。
PreparedStatement 对象对SQL语句进行了预编所以其执行速度要快于Statement 对象因此对此执行SQL语句应使用PreparedStatement 来提高效率。
注意:
1.如果数据类型为时间格式,可采用:
setTimestamp(参数位置,new java.sql.Timestamp(createdate.getTime()));
createdate 为一个对象的实例。
2.如果数据类型为CLOB数据类型,则可以将其作为String类型进行设置。
使用通用类优化数据库操作。
BaseDao类实现的功能 1.获取数据库连接 2执行数据库的怎删改查操作 3.执行每次数据库执行完后的释放工作。
1 package com.basedo; 2 3 import java.sql.Connection; 4 import java.sql.DriverManager; 5 import java.sql.PreparedStatement; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 import javax.naming.Context; 10 import javax.naming.InitialContext; 11 import javax.naming.NamingException; 12 import javax.sql.DataSource; 13 14 import com.pb.news.util.ConfigManager; 15 16 //数据库操作通用类 17 public class BaseDao { 18 public ResultSet rs = null; 19 public PreparedStatement pstmt = null; 20 public Connection con = null; 21 22 // 获得数据库的连接 23 public boolean getConnection() { 24 String driver = ConfigManager.getInstance().getString("jdbc.driver"); 25 String url = ConfigManager.getInstance().getString("jdbc.url"); 26 String username = ConfigManager.getInstance() 27 .getString("jdbc.username"); 28 String password = ConfigManager.getInstance() 29 .getString("jdbc.password"); 30 try { 31 Class.forName(driver); 32 con = DriverManager.getConnection(url, username, password); 33 34 } catch (ClassNotFoundException e) { 35 // TODO Auto-generated catch block 36 e.printStackTrace(); 37 return false; 38 } catch (SQLException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 return false; 42 } 43 return true; 44 } 45 /** 46 * ͨ通过数据源和链接池 47 */ 48 public Connection getConnection2() { 49 //初始化上下文 50 try { 51 Context cxt=new InitialContext(); 52 //获取与数据源相关联的数据源对象 53 DataSource ds=(DataSource) cxt.lookup("java:comp/env/jdbc/books"); 54 con=ds.getConnection(); 55 } catch (NamingException e) { 56 // TODO Auto-generated catch block 57 e.printStackTrace(); 58 } catch (SQLException e) { 59 // TODO Auto-generated catch block 60 e.printStackTrace(); 61 } 62 63 return con; 64 } 65 66 // 增删改的方法 delete from news_detail where id=?and title=? 67 public int executeUpdate(String sql, Object[] params) { 68 int updateRows = 0; 69 getConnection(); 70 try { 71 pstmt = con.prepareStatement(sql); 72 // 填充站位符 73 for (int i = 0; i < params.length; i++) { 74 pstmt.setObject(i + 1, params[i]); 75 } 76 updateRows = pstmt.executeUpdate(); 77 } catch (SQLException e) { 78 // TODO Auto-generated catch block 79 e.printStackTrace(); 80 } 81 return updateRows; 82 83 } 84 85 // 查询 86 public ResultSet executeSQL(String sql, Object[] params) { 87 getConnection(); 88 try { 89 pstmt = con.prepareStatement(sql); 90 // 填充站位符 91 for (int i = 0; i < params.length; i++) { 92 pstmt.setObject(i + 1, params[i]); 93 } 94 rs = pstmt.executeQuery(); 95 } catch (SQLException e) { 96 // TODO Auto-generated catch block 97 e.printStackTrace(); 98 } 99 return rs; 100 101 } 102 103 // 关闭数据库 104 public boolean closeResource() { 105 if (rs != null) { 106 try { 107 rs.close(); 108 } catch (SQLException e1) { 109 // TODO Auto-generated catch block 110 e1.printStackTrace(); 111 return false; 112 } 113 } 114 if (pstmt != null) { 115 try { 116 pstmt.close(); 117 } catch (SQLException e) { 118 // TODO Auto-generated catch block 119 e.printStackTrace(); 120 return false; 121 } 122 } 123 if (con != null) { 124 try { 125 con.close(); 126 } catch (SQLException e) { 127 // TODO Auto-generated catch block 128 e.printStackTrace(); 129 return false; 130 } 131 } 132 return true; 133 134 } 135 }
注意:
在实际开发中BaseDao类只包含数据库访问相关方法而对于数据库访问操作的方法可以单独编写一个专门类来实现。