< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> < %@ page import="java.sql.*" %> < %@ page import="java.io.*" %> <html> <head> <title>ดึงข้อมูล จาก MySQL มาโชว์ </title> </head> <body> < % try { /* ประกาศ ตัวแปล ของการเชื่อมต่อภายใน โดย ระบุชื่อเครื่อง หมายเลขพอร์ต และ ชื่อฐานข้อมูล */ String connectionURL = "jdbc:mysql://localhost:3306/databasename"; // ประกาศค่า connection Connection connection = null; // ประกาศค่า Statement Statement statement = null; // ประกาศค่า resultset ResultSet rs = null; // โหลด JBBC driver "com.mysql.jdbc.Driver" ดังนี้ Class.forName("com.mysql.jdbc.Driver").newInstance(); /* สร้างการติดต่อ โดยใช้ getConnection(ตัวแปลการเชื่อมต่อ,ยูเซอร์,รหัสผ่าน) */ connection = DriverManager.getConnection(connectionURL, "root", "root"); /* สร้าง statements */ statement = connection.createStatement(); // ประกาศ ตัวแปล ในการประมวลผล SQL String QueryString = "SELECT * from tablename"; // ประกาศ ตัวแปล คิวรี่ rs = statement.executeQuery(QueryString); %> <table cellpadding="15" border="1" style="background-color: #ffffcc;"> < % // ใช้ Loop While มันออกมาโชว์ while (rs.next()) { %> <tr> <td>< %=rs.getInt(1)%></td> <td>< %=rs.getString(2)%></td> <td>< %=rs.getString(3)%></td> <td>< %=rs.getString(4)%></td> </tr> < % } %> < % // คำสั่ง ปิดการเชื่อต่อ ทั้งหมด rs.close(); statement.close(); connection.close(); %> </table> < % } catch (Exception ex) { // ถ้าไม่สามารถ เชื่อต่อ ฐานข้อมูลได้ ก็ประกาศ บอก %> <font size="+3" color="red"> <b> < % out.println("แฮ่ๆ ติดต่อฐานข้อมูล ไม่ได้ คร๊าบบบ."); } %> </b> </font> </body> </html>
เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง