JSP程式使用JDBC串連MySQL的教程_JSP編程

來源:互聯網
上載者:User

安裝和載入JDBC驅動程式

下載JDBC驅動程式mysql-connector-java-5.1.7.zip
http://www.jb51.net/softs/214141.html
將裡面的檔案mysql-connector-java-5.1.7-bin.jar放在項目WEB-INF目錄下的lib檔案中,安裝就已經完成了(前提是你的機器已經安裝了MySQL,如果沒有安裝先安裝)

載入在JDBC驅動程式

<%@page language="java" contentType="text/html;charset=gb2312"%><!DOCTYPE html><html>  <head>    <title>載入JDBC驅動程式</title>  </head>  <body>    <%      try{        Class.forName("com.mysql.jdbc.Driver");//載入JDBC驅動程式      }catch(ClassNotFoundException e){        out.println("找不到驅動類");//拋出異常時,提示資訊      }    %>  </body></html>

串連MySQL資料庫
啟動Mysql和Tomcat,

使用JDBC串連資料庫。

第一種方式

<%@page language="java" contentType="text/html;charset=gb2312"%><%@page import="java.sql.*" %><!DOCTYPE html><html>  <head>    <title>連結MySQL資料庫</title>  </head>  <body>    <%      try{        Class.forName("com.mysql.jdbc.Driver");//載入JDBC驅動程式        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaweb?user=root&password=zhangda890126;;");//連結資料庫               }catch(ClassNotFoundException e){        out.println("找不到驅動類");//拋出異常時,提示資訊      }catch(SQLException e){        out.println("連結MySQL資料庫失敗");//處理SQLException異常      }    %>  </body></html>

第二種方式

<%@page language="java" contentType="text/html;charset=gb2312"%><%@page import="java.sql.*" %><!DOCTYPE html><html>  <head>    <title>連結MySQL資料庫</title>  </head>  <body>    <%      String url = "jdbc:mysql://localhost:3306/javaweb";//串連資料庫的url地址      String user = "root";//登入資料庫的使用者名稱      String password = "zhangda890126;;";//登入資料庫的使用者名稱的密碼      try{        Class.forName("com.mysql.jdbc.Driver");//載入JDBC驅動程式        Connection conn = DriverManager.getConnection(url,user,password);//連結資料庫               }catch(ClassNotFoundException e){        out.println("找不到驅動類");//拋出異常時,提示資訊      }catch(SQLException e){        out.println("連結MySQL資料庫失敗");//處理SQLException異常      }    %>  </body></html>

聯繫我們

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