JSP ติดต่อ MySQL

JSP ติดต่อ MySQL
เรียกน้ำย่อย เดี๋ยวจะหาว่า อ่านแล้วไม่สบายเหมือนชื่อเว็บ
จากโค๊ด ข้างล่าง สามารถก๊อป ไปใช้ได้เลย
< %@ page import="java.io.*" %>
< %
try {
/* ประกาศ ตัวแปล ของการเชื่อมต่อภายใน โดย ระบุชื่อเครื่อง หมายเลขพอร์ต และ ชื่อฐานข้อมูล */
String connectionURL = "jdbc:mysql://localhost:3306/databasename";
// ประกาศค่า connection
Connection connection = null;
// โหลด JBBC driver "com.mysql.jdbc.Driver" ดังนี้
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* สร้างการติดต่อ โดยใช้ getConnection(ตัวแปลการเชื่อมต่อ,ยูเซอร์,รหัสผ่าน) */
connection = DriverManager.getConnection(connectionURL, "root", "root");
// เช็คสถานะ การเชื่อต่อ โดยใช้ isClosed()
if(!connection.isClosed())
out.println("สถานะการเชื่อต่อ สำเร็จ " + "MySQL server ทำงานได้ ภายใต้ TCP/IP…");
connection.close();
}
catch(Exception ex){
out.println("ไม่สามารถเชื่อต่อ ฐานข้อมูลได้.");
}
%>
เอาแบบโค๊ด ติดต่อ MySQL แบบ สั้นสุดๆ
< %@ page import="java.io.*" %>
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:portNumber/DatabaseName", "userName", "password");
if(!connection.isClosed()){ out.println("เย้ ติดต่อได้แล้ววววว"); connection.close(); }
else{ out.println("ติดต่อไม่ได้"); }
ดึงข้อมูล จาก MySQL มาโชว์
ขออนุญาต เพิ่ม HTML เข้าไปด้วยเพื่อความสมจริง
< %@ 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>
จะขอเพิ่มความเข้มข้นขึ้น เรื่อยๆ น่ะครับ ต้องค่อยเป็น ค่อยไป ง่ายๆ ก็คือ เวลา มีน้อย 555+


