iT邦幫忙

DAY 9
3

JSP 學習分享系列 第 9

JSP 和MySQL的連結

  • 分享至 

  • xImage
  •  

簡單介紹和Mysql的連線方式 ,使用jdbc ,
jar檔使用NetBeans提供的mysql-connector-java-5.1.6-bin.jar
1.建立一個Demo的資料庫,裡面有一個UserData的資料表

  CREATE DATABASE Demo;
		Use Demo;
		CREATE TABLE UserData(
		UserID varchar(30)  NOT NULL,
		UserPassword varchar(80)  NOT NULL,
		UserName varchar(50)  NOT NULL,
		PRIMARY KEY  (UserID)
  );
  insert into userdata(UserID,UserPassword,UserName) values('Johnny','1111','Johnny');
  insert into userdata(UserID,UserPassword,UserName) values('Mary','2222','Mary');
  insert into userdata(UserID,UserPassword,UserName) values('Jenny','3333','Jenny');
  insert into userdata(UserID,UserPassword,UserName) values('Green','4444','Green');
  insert into userdata(UserID,UserPassword,UserName) values('Lily','5555','Lily');

2.連線之後取得裡面資料
=== exMySQLCon.jsp ===

  <%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %>
<%
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
    try {
      String url = "jdbc:mysql://localhost:3306/demo";
      String user = "root";
      String password = "qwerfdsa";
      String driver = "com.mysql.jdbc.Driver";
      Class.forName(driver);
      con = DriverManager.getConnection(url, user, password);
      stmt = con.createStatement();
      String sql = "select userid,userpassword,username from userdata order by userid";
      rs = stmt.executeQuery(sql);
    } catch (Exception ex) {
      System.out.println(ex);
    }
%>

  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Show All User</title>
  
  
  <%
    if(rs!=null){
      %>
      <table border="1">
        <thead>
          <tr>
            <th>User ID</th>
            <th>User Password</th>
            <th>User Name</th>
          </tr>
        </thead>
        <%
        while(rs.next()){
          String uid = rs.getString(1);
          String upwd = rs.getString(2);
          String uname = rs.getString(3);
        %>
        <tbody>
          <tr>
            <td><%=uid%></td>
            <td><%=upwd%></td>
            <td><%=uname%></td>
          </tr>
        </tbody>
        <%
        }
        %>
      </table>
      <%
    }
  %>
  

上一篇
JSP 和HTML Tag交互使用範例
下一篇
JSP 和 Hibernate 的設定教學第一篇
系列文
JSP 學習分享30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言