0

こんにちは私はデータベースにいくつかのフィールド名を挿入したいので、Java Bean、jsp、サーブレットを使用していますが、エラーが発生します.preparedStatementを使用してからStatementを使用しようとしましたが、どちらの場合もエラーが発生します>お願いしますエラーがどこにあるかを指摘します。私のコードは次のとおりです。EclipsejunoIDEを使用しています。

register1.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import DB.DataBaseConnection;

/**
 * Servlet implementation class register
 */
@WebServlet(register1.REGISTER1)
public class register1 extends HttpServlet {
    static final String REGISTER1 = "/register1";
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public register1() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out=response.getWriter();
        try{
        DataBaseConnection db=new DataBaseConnection();
        java.sql.Connection con= db.connet();
        String FirstName=request.getParameter("FirstName");
        String LastName=request.getParameter("LastName");
        String DOB=request.getParameter("DOB");
        String Qualification=request.getParameter("Qualification");
        String RegistrationNo=request.getParameter("RegistrationNo");
        String CountryOfRegistration=request.getParameter("CountryOfRegistration");
        String PracticeName=request.getParameter("PracticeName");
        String Phone=request.getParameter("Phone");
        String Email=request.getParameter("Email");
        String Address=request.getParameter("Address");
        String Street=request.getParameter("Street");
        String City=request.getParameter("City");
        String State=request.getParameter("State");
        String Country=request.getParameter("Country");
        String PinCode=request.getParameter("PinCode");
        String HowDoYouKnow=request.getParameter("HowDoYouKnow");
        String Comments=request.getParameter("Comments");


out.println(FirstName);







        //ps = (PreparedStatement) con.prepareStatement("insert into registration values(?,?,?)");
Statement st=con.createStatement();
st.executeUpdate("insert into registration values(v,v,v,v,v,v,v,v,v,v,v,v,v,v,v,v,v)");
//      PreparedStatement ps=(PreparedStatement) con.prepareStatement("insert into registration values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//      out.println(FirstName);
//
//  ps.setString(1, FirstName);
//  out.println(FirstName);
//
//  ps.setString(2,LastName);
//  ps.setString(3,DOB);
//  out.println(FirstName);
//
//  ps.setString(4,Qualification);
//  ps.setString(5, RegistrationNo);
//  ps.setString(6, CountryOfRegistration);
//  ps.setString(7, PracticeName);
//  ps.setString(8, Phone);
//  ps.setString(9, Email);
//  ps.setString(10, Address);
//  ps.setString(11, Street);
//  ps.setString(12, City);
//  ps.setString(13, State);
//  ps.setString(14, Country);
//  ps.setString(15, PinCode);
//  ps.setString(16, HowDoYouKnow);
//  ps.setString(17, Comments);
//  ps.executeUpdate();

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

}
}

javabean

package register;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;

import DB.DataBaseConnection;
public class registration {


        private String FirstName;
        private String LastName;
        private String DOB;
        private String Qualification;
        private String RegistrationNo;
        private String CountryOfRegistration;
        private String PracticeName;
        private String Phone;
        private String Email;
        private String Address;
        private String Street;
        private String City;
        private String State;
        private String Country;
        private String PinCode;
        private String HowDoYouKnow;
        private String Comments;
        public registration()
        {
            this.FirstName=FirstName;
            this.LastName=LastName;
            this.DOB=DOB;
            this.Qualification=Qualification;
            this.RegistrationNo=RegistrationNo;
            this.CountryOfRegistration=CountryOfRegistration;
            this.PracticeName=PracticeName;
            this.Phone=Phone;
            this.Email=Email;
            this.Address=Address;
            this.Street=Street;
            this.City=City;
            this.State=State;
            this.Country=Country;this.PinCode=PinCode;this.HowDoYouKnow=HowDoYouKnow;   
            this.Comments=Comments;
        }
        public void setFirstName(String FirstName)
        {
            this.FirstName=FirstName;
        }
        public String getFirstName()
        {
            return FirstName;
        }
        public void setLastName(String LastName)
        {
            this.LastName=LastName;
        }
        public String getLastName()
        {
            return LastName;
        }public void setDOB(String DOB)
        {
            this.DOB=DOB;
        }
        public String getDOB()
        {
            return DOB;
        }public void setQualification(String Qualification)
        {
            this.Qualification=Qualification;
        }
        public String getQualification()
        {
            return Qualification;
        }public void setRegistrationNo(String RegistrationNo)
        {
            this.RegistrationNo=RegistrationNo;
        }
        public String getRegistrationNo()
        {
            return RegistrationNo;
        }public void setCountryOfRegistration(String CountryOfRegistration)
        {
            this.CountryOfRegistration=CountryOfRegistration;
        }
        public String getCountryOfRegistration()
        {
            return CountryOfRegistration;
        }public void setPracticeName(String PracticeName)
        {
            this.PracticeName=PracticeName;
        }
        public String getPracticeName()
        {
            return PracticeName;
        }public void setPhone(String Phone)
        {
            this.Phone=Phone;
        }
        public String getPhone()
        {
            return Phone;
        }public void setEmail(String Email)
        {
            this.Email=Email;
        }
        public String getEmail()
        {
            return Email;
        }public void setAddress(String Address)
        {
            this.Address=Address;
        }
        public String getAddress()
        {
            return Address;
        }public void setStreet(String Street)
        {
            this.Street=Street;
        }
        public String getStreet()
        {
            return Street;
        }public void setCity(String City)
        {
            this.City=City;
        }
        public String getCity()
        {
            return City;
        }public void setState(String State)
        {
            this.State=State;
        }
        public String getState()
        {
            return State;
        }public void setCountry(String Country)
        {
            this.Country=Country;
        }
        public String getCountry()
        {
            return Country;
        }public void setPinCode(String PinCode)
        {
            this.PinCode=PinCode;
        }
        public String getPinCode()
        {
            return PinCode;
        }public void setHowDoYouKnow(String HowDoYouKnow)
        {
            this.HowDoYouKnow=HowDoYouKnow;
        }
        public String getHowDoYouKnow()
        {
            return HowDoYouKnow;
        }public void setComments(String Comments)
        {
            this.Comments=Comments;
        }
        public String getComments()
        {
            return Comments;
        }
        public String insert() throws ClassNotFoundException 
        {
            String output="";
        //public void insert(String FirstName,String LastName,String DOB) throws SQLException
        //{
        //DataBaseConnection db= new DataBaseConnection();
        //Connection con =(Connection) db.connet();
        //PreparedStatement ps=(PreparedStatement) con.prepareStatement("insert into registration values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        //PreparedStatement ps;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test","sukanth","");
            //ps = (PreparedStatement) con.prepareStatement("insert into registration values(?,?,?)");
            PreparedStatement ps=(PreparedStatement) con.prepareStatement("insert into registration values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

        ps.setString(1, FirstName);
        ps.setString(2,LastName);
        ps.setString(3,DOB);

        ps.setString(4,Qualification);
        ps.setString(5, RegistrationNo);
        ps.setString(6, CountryOfRegistration);
        ps.setString(7, PracticeName);
        ps.setString(8, Phone);
        ps.setString(9, Email);
        ps.setString(10, Address);
        ps.setString(11, Street);
        ps.setString(12, City);
        ps.setString(13, State);
        ps.setString(14, Country);
        ps.setString(15, PinCode);
        ps.setString(16, HowDoYouKnow);
        ps.setString(17, Comments);
        ps.executeUpdate();
        output="sucess";

        }
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            output=e.toString();
        }
        /*public static void main(String args[]) throws SQLException
        {
            registration r=new registration();
            r.insert("s","k","n");
        }*/
        return output;
    }
//      public static void main(String args[]) throws SQLException, ClassNotFoundException
//      {
//          registration r=new registration();
//          r.insert();
//      }

}

データはこのjspから取得されます

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><jsp:useBean id="registration" class="register.registration" scope="request">
<jsp:setProperty property="*" name="registration"/></jsp:useBean>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action ="register1" method="post">
FirstName<input type="text" name="FirstName">Lastname<input type="text" name="LastName"><br>
DOB<input type="text" name="DOB">Qualification<input type="text" name="Qualification"><br>
RegistrationNo<input type="text" name="RegistrationNo">CountryOfRegistration<input type="text" name="CountryOfRegistration"><br>
PracticeName<input type="text" name="PracticeName">Phone<input type="text" name="Phone"><br>
Email<input type="text" name="Email">Address<input type="text" name="Address"><br>
Street<input type="text" name="Street">City<input type="text" name="City"><br>
State<input type="text" name="State">Country<input type="text" name="Country"><br>
PinCode<input type="text" name="PinCode">HowDoYouKnow<input type="text" name="HowDoYouKnow"><br>
Comments<input type="text" name="Comments"><br>
<input type ="submit" name ="submit">
<input type="reset" name="reset">

</form>
</body>
</html>

これはエラーです

Mar 26, 2013 5:48:53 AM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre/lib/i386/client:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre/lib/i386:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre/../lib/i386:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre/lib/i386/client:/usr/lib/jvm/java-1.6.0-openjdk-1.6.0.0/jre/lib/i386::/usr/java/packages/lib/i386:/lib:/usr/lib
Mar 26, 2013 5:48:54 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:project1' did not find a matching property.
Mar 26, 2013 5:48:54 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:project2' did not find a matching property.
Mar 26, 2013 5:48:54 AM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:project3' did not find a matching property.
Mar 26, 2013 5:48:54 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 26, 2013 5:48:54 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 26, 2013 5:48:54 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 2844 ms
Mar 26, 2013 5:48:55 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 26, 2013 5:48:55 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.37
Mar 26, 2013 5:48:55 AM org.apache.catalina.util.SessionIdGenerator createSecureRandom
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [117] milliseconds.
Mar 26, 2013 5:48:56 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 26, 2013 5:48:56 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 26, 2013 5:48:56 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1493 ms
java.lang.NullPointerException
    at register1.doPost(register1.java:77)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:679)
java.lang.NullPointerException
    at register1.doPost(register1.java:77)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:679)
java.lang.NullPointerException
    at register1.doPost(register1.java:77)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:679)
java.lang.NullPointerException
    at register1.doPost(register1.java:77)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:679)

これはDataBaseConnectionクラスです

package DB;
import  java.sql.*;
public class  DataBaseConnection
{public static void main(String[] args) throws SQLException, ClassNotFoundException
    {

    DataBaseConnection db= new DataBaseConnection();
    Connection  con=db.connet();
        if(!con.isClosed())
        {
            System.out.println("connectedn");
        }
        }
public Connection connet() 
{
    Connection con=null;

    try
    {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","sukanth","");
return con;
    }
    catch(Exception e)
    {
        return  con;
    }



}
}
4

3 に答える 3

1
java.lang.NullPointerException
    at register1.doPost(register1.java:77)

エラーは明らかNullPointerException

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        PrintWriter out=response.getWriter();
        try{
        DataBaseConnection db=new DataBaseConnection();
        java.sql.Connection con= db.connet();
        //...... 
       //Statement st=con.createStatement(); // This may be the root cause of exception
       // check null here
      if(con!=null){
        // create statement or prepared statement
      }  
} 

変更されたDataBaseConnection.java

package DB;
import java.sql.*;
public class DataBaseConnection {
    public Connection connet() {
        Connection con=null;
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","sukanth","");
        }
        catch(Exception e)
        {
            e.printStacktrace();
        }
        return con;
    }
}

また、mysqljdbc.jarCLASSPATHに含まれていることを確認してください。でコピーmysqljdbc.jarWEB-INF/libます。

于 2013-03-26T05:20:14.360 に答える
1

Class.forName()Register1.javaにドライバをロードするためのを提供していません

Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","sukanth","");
Statement st=con.createStatement();
//remaining codes

JSPページにすべての値を指定していることを確認してください。また、サーブレットにファイルされたDOBを日付形式に変換しない場合は、データベースのDOBフィールドが文字列であることを確認してください。

于 2013-03-26T05:38:01.070 に答える
0

I think you simply mixed up the code. You put the connection and insertion related logic in your登録クラス, then what is there in DataBaseConnection class and what is its role? You are not clear with this code. Whatever登録クラスinsetrt()method is doing the same you are doing indoPost(-、-)`サーブレットのメソッド。

フォームコンポーネントの値を設定および取得するためにBeanクラスを取得する必要はないと思います。DB接続を確立するためのメソッドと接続を解放するためのメソッドの2つのメソッドを含むBeanクラスを取得するだけです。サーブレットのdoGet(-、-)メソッドでオブジェクトを作成し、request.getParameter(-)を使用して行ったようにすべてのフォームコンポーネントの値を読み取り、pstmnt.setXxx()を使用してそれらの値をクエリのプレースホルダーに設定し、クエリを実行します。 。正常に実行されたら、Beanクラスの2番目のメソッドを呼び出して、接続を解放します。

これを試してみてください、私はそれが役立つことを願っています...

    //write a bean class in some package(p1)
    package p1;
    //import all required classes/interfaces
    public class DBConn{
    private Connection con;
    public Connection getConnection() throws SQLException{
    Class.forName("com.mysql.jdbc.Driver");
    con= DriverManager.getConnection("jdbc:mysql://host_ipaddress:port no./sid","username","password");
    return con;
    }

    public void releaseConnection() throws SQLException{

     if(con!=null)
     con.close();
      }
    }

//Take a form page(jsp/html) same as you have....

//write a servlet to insert the form page data in DB..


//import all classes and interfaces here...
public class register1 extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
  try{  
        // set content type and get an output stream...      
        response.setContentType("text/html");
        PrintWriter out=response.getWriter();

        //create bean class object and get a connection object...
        DBConn db=new DBConn();
        java.sql.Connection con= db.getConnection();

        // read all request parameter values from request...
        String FirstName=request.getParameter("FirstName");
        String LastName=request.getParameter("LastName");
        String DOB=request.getParameter("DOB");
        String Qualification=request.getParameter("Qualification");
        String RegistrationNo=request.getParameter("RegistrationNo");
        String CountryOfRegistration=request.getParameter("CountryOfRegistration");
        String PracticeName=request.getParameter("PracticeName");
        String Phone=request.getParameter("Phone");
        String Email=request.getParameter("Email");
        String Address=request.getParameter("Address");
        String Street=request.getParameter("Street");
        String City=request.getParameter("City");
        String State=request.getParameter("State");
        String Country=request.getParameter("Country");
        String PinCode=request.getParameter("PinCode");
        String HowDoYouKnow=request.getParameter("HowDoYouKnow");
        String Comments=request.getParameter("Comments");

        // get a pre-compiled query with the help of PreparedStatement ...
        PreparedStatement ps =con.prepareStatement("insert into <table name>
values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

   //set the place holder parameters values to the pre-compiled query..
    ps.setString(1, FirstName);
    ps.setString(2,LastName);
    ps.setString(3,DOB);
    ps.setString(4,Qualification);
    ps.setString(5, RegistrationNo);
    ps.setString(6, CountryOfRegistration);
    ps.setString(7, PracticeName);
    ps.setString(8, Phone);
    ps.setString(9, Email);
    ps.setString(10, Address);
    ps.setString(11, Street);
    ps.setString(12, City);
    ps.setString(13, State);
    ps.setString(14, Country);
    ps.setString(15, PinCode);
    ps.setString(16, HowDoYouKnow);
    ps.setString(17, Comments);
  int counter= ps.executeUpdate();

    if(counter>0)
    {
     out.println("Values inserted successfully...");
    db.releaseConnection();
    }
  else if(counter<=0)
   {
    out.println("Something went wrong, Values couldn't inserted in DB..");
    db.releaseConnection();
   }

    }
    catch(SQLException sqle)
    {
        sqle.printStackTrace();
    }
   catch(ServletException se)
   {
   se.printStackTrace();
    }
   catch(IOException ie)
   {
    ie.printStackTrace();
   }
   catch(Exception e)
   {
    e.printStackTrace();
   }

  }//doGet(-,-) closing.....

  protected void doPost(HttpServletRequest request, HttpServletResponse response) {
     doGet(request,response);
    }//doPost(-,-) closing...
}// servlet class closing...

//サーブレットをURLにマップし、フォームページでフォームタグのアクション値と同じものを使用することを忘れないでください。MYSQL関連のConnector / J jarファイルは、アプリケーションまたはサーバーのlibフォルダーのクラスパスとlibフォルダーにあります。 (アプリケーションのlibフォルダーに配置した方がよい)。それがあなたに明確になることを願っています。

于 2013-03-26T05:06:20.740 に答える