This is document prepare for practice example course Web-Based Java Applications
.
DBContext
package com.context;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBContext {
/*USE BELOW METHOD FOR YOUR DATABASE CONNECTION FOR BOTH SINGLE AND MULTILPE SQL SERVER INSTANCE(s)*/
/*DO NOT EDIT THE BELOW METHOD, YOU MUST USE ONLY THIS ONE FOR YOUR DATABASE CONNECTION*/
public Connection getConnection()throws Exception {
String url = "jdbc:sqlserver://"+serverName+":"+portNumber +";databaseName="+dbName;
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
return DriverManager.getConnection(url, userID, password);
}
/*Insert your other code right after this comment*/
/*Change/update information of your database connection, DO NOT change name of instance variables in this class*/
private final String serverName = "localhost"; //127.0.0.1
private final String dbName = "......";
private final String portNumber = "1433";
private final String userID = "sa";
private final String password = "123456";
}
Insert
public void .........(String ........., in.........) {
Connection con = null;
DBContext db = new DBContext();
try {
con = db.getConnection();
String sql = "INSERT INTO ........(......) VALUES (?, ?)";
PreparedStatement stmt con.prepareStatement(sql);
stmt.setString(1, .........);
stmt.setInt(2, .........);
stmt.executeUpdate();
stmt.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Select
public int .........(String .........) {
Connection con = null;
DBContext db = new DBContext();
try {
con = db.getConnection();
Statement stmt = con.createStatement();
String sql = "SELECT ......... FRO......... WHERE ........ ='........";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int ........ = rs.getInt(1);
return studentId;
}
rs.close();
stmt.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}
Update
public void .........(String ........., in.........) {
Connection con = null;
DBContext db = new DBContext();
try {
con = db.getConnection();
String sql = "UPDATE ......... SE......... = ? WHERE ......... = ?";
PreparedStatement stmt con.prepareStatement(sql);
stmt.setString(1, .........);
stmt.setInt(2, .........);
stmt.executeUpdate();
stmt.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Delete
public void .........(String id) {
Connection con = null;
DBContext db = new DBContext();
try {
con = db.getConnection();
String sql = "DELETE FROM ........WHERE ......... = ?";
PreparedStatement stmt con.prepareStatement(sql);
stmt.setString(1, id);
stmt.executeUpdate();
stmt.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return;
}
Wellcome file
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>