zoukankan      html  css  js  c++  java
  • MySql数据源配置

    1.tomcat的config/server.xml中将以下代码写到 </Host>前:

    <Context docBase="struts1" path="/struts1" reloadable="true" source="org.eclipse.jst.jee.server:struts1">     <!--struts1为工程名-->
    <Resource
     name="jdbc/demoDS">     <!--name与web.xml中name要一致,其中demoDS还要与后文中java代码(javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/demoDS");部分一致-->
     scope="Shareable"
     type="javax.sql.DataSource"
     factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
     url="jdbc:mysql://localhost:3306/test"     <!--test为数据库名-->
     driverClassName ="com.mysql.jdbc.Driver"
     username="root"
     password="123456"
    />

    2.web.xml中引入数据源(三个参数顺序不能变,否则编译不通过)

    <resource-ref>    
           <res-ref-name>jdbc/demoDS</res-ref-name>    
           <res-type>javax.sql.DataSource</res-type>  
           <res-auth>Container</res-auth> 

    </resource-ref>

    3.写java代码连接

    package util;
    import java.sql.Connection;
    public class Struts
     {
        protected javax.naming.Context ctx = new javax.naming.InitialContext();
        protected javax.sql.DataSource ds;
         protected Connection conn;
         public Struts() throws Exception
         {
             ds = (javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/demoDS");
             conn = ds.getConnection(); 
        }
     }

    4.应用示例代码,写一个查询函数

     public List<String[]> search() throws Exception
           {
               List<String[]> result = new LinkedList<String[]>();
               String sql = "SELECT * FROM Stu_Course WHERE SNo='"
    + form.getCNo() +"'";
               PreparedStatement pstmt =  conn.prepareStatement(sql);
               ResultSet rs = pstmt.executeQuery(); 
              while(rs.next())
               {
                   String[] row = new String[4];
                   row[0] = rs.getString(1);
                   row[1] = rs.getString(2);
                   row[2] = String.valueOf(rs.getInt(3));
                   row[3] = rs.getString(4);
                   result.add(row);
               }
               rs.close();
               conn.close();
               return result;
           }

    蛋疼的,以前弄过就忘,再用到就有蛋疼一遍,记下来。。。

            

  • 相关阅读:
    [python]OS文件系统
    [phyton]文件的简单读写练习
    [Python]字典的简单用法
    Cocos2d-x学习笔记(十五)之 绘制图形
    Cocos2d-x学习笔记(十四)之 拖动渐隐效果类CCMotionStreak
    Cocos2d-x学习笔记(十三)之 容器类
    Cocos2d-x学习笔记(十二)之 文本渲染类
    Cocos2d-x学习笔记(十一)之 菜单类CCMenu
    Cocos2d-x学习笔记(十)之 控件类CCControl
    Cocos2d-x学习笔记(九)之 摄像机类CCCamera
  • 原文地址:https://www.cnblogs.com/ximencuixue/p/4147663.html
Copyright © 2011-2022 走看看