MySql資料來源配置

來源:互聯網
上載者:User

標籤:style   io   ar   color   os   sp   for   java   on   

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;
       }

蛋疼的,以前弄過就忘,再用到就有蛋疼一遍,記下來。。。

 

 

        

MySql資料來源配置

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.