Jsp頁面串連MySQL資料庫

來源:互聯網
上載者:User
js|mysql|資料|資料庫|頁面   
MySQL驅動程式:mysql-connector-java-3.1.7.tar.gz
J2SE版本:5.02
Tomcat版本:5.0.30
MySQL:4.1.10 或者是 3.23.49 (我使用的版本)
首先,解壓縮MySQL驅動程式,在\mysql-connector-java-3.1.7下有一個mysql-connector-java-3.1.7-bin.jar 包。將它拷貝到 
JAVA的安裝目錄D:\Program\Java
D:\Program Files\Java\jre1.5.0_02\lib\ext 下(調試Java程式使用)
和D:\Program Files\Java\jdk1.5.0_02\jre\lib\ext下(Tomcat程式使用,也可以拷貝到%CATALINA%\common\lib下)
還有一種方法就是自己找一個目錄存放MySQL驅動。在系統的環境變數中把路徑加到path中。
一個Java Application例子。 
//LoadDriver
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.SQLException; 
// Notice, do not import com.mysql.jdbc.* 
// or you will have problems! 
public class LoadDriver { 
    public static void main(String[] args) { 
        try { 
            // The newInstance() call is a work around for some 
            // broken Java implementations
            Class.forName("com.mysql.jdbc.Driver").newInstance(); 
            } 
        catch (Exception ex) { 
            System.out.println(ex);
        }
    }
}
調試後,運行LoadDriver.class如果沒有拋出異常則說明JavaAplication程式的驅動配置成功了
一個JSP例子 
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
     <%  Connection con;
          Statement sql;
          ResultSet rs;
          try{
              Class.forName("com.mysql.jdbc.Driver").newInstance();
          }
          catch(ClassNotFoundException e){
          e.getMessage();
          }
          try{
              con=DriverManager.getConnection("jdbc:mysql://localhost/mysql?
                                         user=&password=&useUnicode=true&characterEncoding=GBK"); 
              sql=con.createStatement();
              rs=sql.executeQuery("SELECT * FROM user");
              out.print("<Table Border>");
              out.print("<tr>");
              out.print("<TH width=100>"+"姓名");
              out.print("<TH width=100>"+"密碼");
              out.print("</tr>");
              while(rs.next()){ 
                  out.print("<TR>");
                  out.print("<TD>"+rs.getString(1)+"</TD>");
                  out.print("<TD>"+rs.getString(2)+"</TD>");
                  out.print("</TR>");
              }
             out.print("</Table>");
             con.close();
         }
         catch(Exception e){
             e.getMessage();
         }
     %>
</body>
</html>
檔案儲存到%CATALINA_HOME%\webapps\ROOT下。啟動Tomcat伺服器,調試檔案如果不出現異常,就配置成功了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.