使用servlet和JavaBean訪問(wèn)MySQL

字號(hào):

使用Servlet和Java Bean訪問(wèn)MySQL
    運(yùn)行環(huán)境: JDK 5.0 + Tomcat 5.5.4
    JDK安裝路徑: D:\Java\jdk1.5.0_01
    Tomcat安裝路徑:D:\Tomcat 5.5
    設(shè)置環(huán)境變量(控制面板->系統(tǒng)->高級(jí)):
    java_home=D:\Java\jdk1.5.0_01
    path=%JAVA_HOME%\bin
    classpath=.;D:\Java\jdk1.5.0_01\lib\dt.jar;D:\Java\jdk1.5.0_01\lib\tools.jar;D:\Tomcat 5.5\common\lib\servlet-api.jar;D:\Tomcat 5.5\common\lib\mysql-connector-java-3.1.6-bin.jar;
    其中D:\Tomcat 5.5\common\lib\servlet-api.jar為T(mén)omcat的servlet API實(shí)現(xiàn),一定要加上,不如無(wú)法編譯servlet
    D:\Tomcat 5.5\common\lib\mysql-connector-java-3.1.6-bin.jar;是MySQL的JDBC驅(qū)動(dòng),connect/J 3.1.6,可到MySQL官方網(wǎng)站下載
    Tomcat5.5虛擬目錄設(shè)定:
    D:\Tomcat 5.5\conf\Catalina\localhost下新加一test.XML
    內(nèi)容如下:
    
    

    d:\www路徑將是我們測(cè)試網(wǎng)站的根目錄,通過(guò)http://localhost:8080/test訪問(wèn)該虛擬目錄
    d:\www下建有目錄Web-INF,下有web.xml設(shè)置文件(可參考D:\Tomcat 5.5\webapps\ROOT\WEB-INF\web.xml),classes目錄和lib目錄
    //連接數(shù)據(jù)庫(kù)的Java Bean文件名dbconn.java
    package NinGoo;
    import java.sql.*;
    public class dbconn {
    public dbconn() {
    }
    //declare variable
    private Connection conn = null;
    ResultSet rs = null;
    private String server = "127.0.0.1";
    private String port = "3306";
    private String db = "test";
    private String user = "root";
    private String pass = "password";
    private String drivername="com.mysql.jdbc.Driver";
    private String URL="jdbc:mysql://"+server+":"+port+"/"+db+"?user="+user+"&password="+pass;
    public Connection getConn(){//get database connection
    try{
    Class.forName(drivername).newInstance();
    conn = DriverManager.getConnection(URL);
    }
    catch(Exception e){
    e.printStackTrace();
    }
    return this.conn ;
    }
    public ResultSet executeSQL(String str) {
    try{
    Statement stmt = conn.createStatement();
    rs = stmt.executeQuery(str);
    }
    catch(Exception e){
    e.printStackTrace();
    }
    return this.rs;
    }
    }
    編譯javac welcome.java,將編譯后的文件welcome.class放到目錄D:\www\WEB-INF\classes\NinGoo\下
    //調(diào)用Java Bean的servlet welcome.java
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;