1. 程式人生 > >tomcat上配置資料庫連線和專案部署

tomcat上配置資料庫連線和專案部署

分三步:
1、到tomcat目錄下conf資料夾裡面的server.xml部署專案
2、到tomcat目錄下conf資料夾裡面的context.xml設定資料庫連線
3、專案內寫呼叫context.xml的類

server.xml

<Context path="/專案名" docBase="專案路徑" reloadable="true">
</Context>

context.xml

<Resource
    name="jdbc/專案名"
    auth="Container"
    type ="javax.sql.DataSource"
    driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost:3306/xxxxx" username = "dbuser" password = "dbpassword" />

DbBean.java(先匯入mysql的連線jar包到專案中)

import java.sql.*;
import javax.sql.*;

public class DbBean {

    private Connection dbCon;

    String dbURL = "jdbc:mysql://localhost:3306/xxxxx";
    String dbDriver = "com.mysql.jdbc.Driver"
; String dbUser = "dbuser"; String dbPassword = "dbpassword"; public DbBean() { super(); } public boolean connect() throws ClassNotFoundException, SQLException { try{ Context initCtx = new InitialContext(); if(initCtx == null ){ throw
new Exception("No Context"); } Context ctx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource)ctx.lookup("jdbc/專案名"); //專案名要與context.xml裡面的對應 if(ds != null){ dbCon = ds.getConnection(); dbCon.setAutoCommit(false); return true; }else{ return false; } }catch(javax.naming.NoInitialContextException e){ //以防萬一 tomcat上配置的context.xml用不了 Class.forName(this.getDbDriver()); dbCon = DriverManager.getConnection(this.getDbURL() , dbUser ,dbPassword); dbCon.setAutoCommit(false); return true; }catch(Exception e){ return false; } } }

到這裡就已經可以連線資料庫了 剩下的就是在DbBean裡面加上自己要的程式碼