jdbc 操做数据库

一、创建链接池:在\tomcat6\conf中的context.xml文件中的<context>中添加下面语句
oracle:
  <Resource name="jdbc/oracleds"
            auth="Container"
            type="javax.sql.DataSource"
            maxActive="100"
            maxIdle="30"
            maxWait="10000"
            username="scott"
            password="yanyan"
             driverClassName="oracle.jdbc.driver.OracleDriver"
            url="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
mysql: <Resource name="jdbc/mysqlds"             auth="Container"             type="javax.sql.DataSource"             maxActive="100"             maxIdle="30"             maxWait="10000"             username="scott"             password="yanyan"              driverClassName="com.mysql.jdbc.Driver"             url="jdbc:mysql://127.0.0.1/orcl"/> 2,把数据库的驱动类库添加到tomcat中的类库中 三、操做:以下: public void doPost(HttpServletRequest request, HttpServletResponse response)             throws ServletException, IOException {         request.setCharacterEncoding("UTF-8");//解决中文乱码         String title = request.getParameter("title");         String content = request.getParameter("content");         String categoryID = request.getParameter("category");                 DataSource ds = null;         try {             // 经过在context.xml文件,设定的数据源对象的名字,获取数据源对象             Context context = new InitialContext();             ds = (DataSource) context.lookup("java:/comp/env/jdbc/oracleds");         } catch (Exception e) {             System.out.println("获取数据源时出错");         }         int result = 0;         try {             Connection cn=ds.getConnection();             // 添加博文的SQL语句,now()生成当前系统时间             String sql = "insert into blog(id,title,content,catagory_id,created_time) values (B_SID.NEXTVAL,'锦衣卫','锦衣卫',2,sysdate)"; //如今我还不知道怎么用序列实现表序号自动添加             // 为SQL语句中的?设定参数                       PreparedStatement psmt=cn.prepareStatement(sql);             psmt.setString(1, title);             psmt.setString(2, content);             psmt.setInt(3,Integer.parseInt(categoryID));             result=psmt.executeUpdate();             } catch (SQLException e) {             e.printStackTrace();         }         String message = "";         if (result == 1) {             message = "添加博文成功!";         } else {             message = "添加博文失败!";         }         System.out.print(message);                 }
相关文章
相关标签/搜索