方法preparestatement(String)是未定义的错误

时间:2014-08-15 11:49:41

标签: java eclipse prepared-statement

以下是我的servlet:

import java.io.IOException;
import java.sql.*;

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 connection.Connection;

@WebServlet("/Check")
public class Check extends HttpServlet {
private static final long serialVersionUID = 1L;


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

Connection con;
//PreparedStatement pstmt=con.prepareStatement("Insert into account_master(name,acct_opn_date,cif_id,address) values(?,?,?,?)");
PreparedStatement pstmt= con.prepareStatement("Insert into account_master(name,acct_opn_date,cif_id,address) values(?,?,?,?)");
}

在最后一个语句中,我在Eclipse中遇到错误

**此行有多个标记

  • 观察点:检查[访问和修改] - pstmt
  • 方法prepareStatement(String)未定义类型  连接**

以下是我的连接类:

package connection;
import java.sql.*;

public class Connection {

public static void main(String args[])
{
    String username="system";
    String password="root";
try{

    Class.forName("oracle.jdbc.driver.OracleDriver");
    try {
          DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",username,password);
        //DriverManager.getConnection("jdbc:oracle:thin:system/root@localhost:1521:XE");
    } catch (SQLException e) {

        System.err.println("Problem in connection");
        e.printStackTrace();
    }
}
catch(ClassNotFoundException ex)
{
    System.err.println("Error loading driver");
}
}

}

1 个答案:

答案 0 :(得分:1)

您将JDBC Connection类与您自己的连接类混淆。

您可以将连接类重命名为ConnectionBuilder类:

public class ConnectionBuilder {
    String username="system";
    String password="root";

    public static Connection buildConnection () {
        try{
           Class.forName("oracle.jdbc.driver.OracleDriver");
           try {
               return DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",username,password);
           } catch (SQLException e) {
               System.err.println("Problem in connection");
               e.printStackTrace();
                return null; // better throw an exception
           }
        } catch(ClassNotFoundException ex) {
            System.err.println("Error loading driver");
            return null; // better throw an exception
        }
    }
}

你的Check类应该使用这个方法:

PreparedStatement pstmt = ConnectionBuilder.buildConnection().prepareStatement(...);