1. Create a new generic Java file under the source package named Myconnection.java:
Package weinidingservlet; Package Name
import java.sql.* / /need to introduce SQL package to perform database operation
import Java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
Import Java.util.logging.Level;
Import Java.util.logging.Logger;
import weinidingjavadata.wndmembers; //This is a Wndmembers class generated by the database
Import com.mysql.jdbc.Connection; // Need to introduce MySQL driver package
Import com.mysql.jdbc.Statement;
/**
*
* @author Spring FEI
*/
Public class myconnection {
Connection conn =null;
preparedstatement stat=null; // Defined as stat for dynamic preprocessing SQL statement class
ResultSet Rs=null;
Static MyConnection Instance=null;
Public MyConnection () {
Init ();
}
Public void init ()//function to initialize the MyConnection class
{
try {
class.forname ("Com.mysql.jdbc.Driver");
conn= (Connection) drivermanager.getconnection ("JDBC:MYSQL://IP Address/Database name", "Database authorized user name", "password");
SYSTEM.OUT.PRINTLN (conn);
} catch (ClassNotFoundException ex) {
Logger.getlogger (MyConnection.class.getName ()). log (Level.severe, NULL, ex);
} catch (SQLException ex) {
Logger.getlogger (MyConnection.class.getName ()). log (Level.severe, NULL, ex);
}
}
public static MyConnection getinstance () {
if (instance==null)
Instance=new myconnection ();
return instance;
}
Public void Insert (Wndmembers member)Throws SQLException//Define an Insert function, which is an entity class object generated by the database
{
init (); Perform initialization in the Insert function
String username=member.getwndmembersname ();
String PW=MEMBER.GETWNDMEMBERSPW (); Receive parameters passed from the servlet
String sql = "INSERT into Wnd_members (WND_MEMBERSNAME,WND_MEMBERSPW) VALUES (?,?)"; Defining SQL Statements
SYSTEM.OUT.PRINTLN (SQL);
stat=conn.preparestatement (SQL);
stat.setstring (1, username);
stat.setstring (2, PW);
stat.executeupdate (); Perform an insert operation
if (stat!=null) {stat.close ();}
}
}
Java EE database connection and insertion