【问题标题】:Trouble with connection SQL database to JAVA in NetBeans在 NetBeans 中将 SQL 数据库连接到 JAVA 时出现问题
【发布时间】:2014-05-23 05:12:47
【问题描述】:

我尝试用 SQL 连接 netbeans,但还是有问题。我想,还是少了点什么。

在这里,我创建了这个类: (这里现在发生错误 - 另一方面,我真的不知道,如果它是完全正确的)

public class connection {
   public Connection con;

   public void dbConnect(){

     try {  
       Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
       String connectionUrl = "jdbc:sqlserver://FIO\\SQLEXPRESS;" +
           "databaseName=Feedback;integratedSecurity=true";
       con = DriverManager.getConnection(connectionUrl);
    } catch (SQLException e) {
        System.out.println("SQL Exception: "+ e.toString());
    } catch (ClassNotFoundException cE) {
        System.out.println("Class Not Found Exception: "+ cE.toString());   
    }

    }
    public Connection getConnection() {
        return con;
    }

    static PreparedStatement prepareStatement(String sql) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

}

然后,在另一个名为 Questions 的类中,我尝试准备语句并从数据库加载信息:

public class Questions {

public void doQuestion()
{...
 ...
 ...
 ...
 connection con = new connection(); 
 con.dbConnect();

 PreparedStatement preparedStatement;


    try{


      **preparedStatement = con.getConnection().createStatement();**


    String sql = "SELECT Answer FROM Feedback.dbo.Question1 WHERE TrainerFirstName=? AND TrainerLastName=?"



    preparedStatement.setString(1,"ffname");

    preparedStatement.setString(2, "llname");

    ResultSet result = preparedStatement.executeQuery(sql);


     while(result.next()) 
     {
     System.out.println(result.getString(1) + result.getString(2));
      }


      }catch (SQLException ex) {
          Logger.getLogger(Questions.class.getName()).log(Level.SEVERE, null, ex);
       }
         ...
          ...
           ...
             ...
              ...
          }
          }

Netbeans 下划线:"preparedStatement = con.getConnection().createStatement(); ", due to "incompatible types: Statement cannot be converted to PreparedStatement."

我无法克服它。

然后我尝试做这样的事情来解决问题,但问题仍然存在,即使以不同的方式。:

       public class Questions {

         public void doQuestion()

       {...
        ...
         ...
           ...
          connection con = new connection(); 
          con.dbConnect();

          Statement statement;
    try {
        statement = con.getConnection().createStatement();

     String sql = "SELECT Answer FROM Feedback.dbo.Question1 WHERE TrainerFirstName=?      AND TrainerLastName=?"


        **statement.setString(1,"ffname");
        statement.setString(2, "llname");**

        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()) {
            System.out.println(rs.getString(1) + rs.getString(2));
        }

    } catch (SQLException ex) {
        Logger.getLogger(Questions.class.getName()).log(Level.SEVERE, null, ex);
    }

在这里,Netbeans 下划线 "statement.setString(1,"ffname"); statement.setString(2, "llname");"

由于标签:”找不到符号 符号:方法 setString(int,String) location:variable Statement of type Statement"

然后,我尝试以不同的形式发送 String sql:

           String sql = "SELECT Answer FROM Feedback.dbo.Question1 WHERE TrainerFirstName="+ffname+"AND TrainerLastName="+llname

并以这种方式在代码中省略:
statement.setString(1,"ffname"); statement.setString(2, "llname");

所以,代码看起来像这样:

          public class Questions {

         public void doQuestion()

       {...
        ...
         ...
           ...
          connection con = new connection(); 
          con.dbConnect();

          Statement statement;
    try {
        statement = con.getConnection().createStatement();

         String sql = "SELECT Answer FROM Feedback.dbo.Question1 WHERE TrainerFirstName="+ffname+"AND TrainerLastName="+llname


        ResultSet rs = statement.executeQuery(sql);

        while (rs.next()) {
            System.out.println(rs.getString(1) + rs.getString(2));
        }

    } catch (SQLException ex) {
        Logger.getLogger(Questions.class.getName()).log(Level.SEVERE, null, ex);
    }

这样,一切似乎都OK了,但是当我运行一个项目时,出现错误并指向:“ statement = con.getConnection().createStatement(); ”并且程序当然崩溃了。

我真的不知道该怎么办。

如果有人有想法,请写出来。

非常感谢。

【问题讨论】:

  • 你需要改为conn.prepareStatement()

标签: java sql netbeans connection


【解决方案1】:

这是 netbeans 的一个preparedstament 的例子

Connection con = null;
PreparedStatement ptmt = null;

public void add(Archivos archivos) {

    try {
        String query = "INSERT INTO archivosemisor "
                + "(rfcEmisor, cer, llave, password, idError, resultado)"
                + " VALUES (?,?,?,?,?,?)";
        con = getConnection();
        ptmt = con.prepareStatement(query);
        ptmt.setString(1, archivos.getRfcEmisor());
        ptmt.setString(2, archivos.getCer());
        ptmt.setString(3, archivos.getLlave());
        ptmt.setString(4, archivos.getPassword());
        ptmt.setString(5, archivos.getIdError());
        ptmt.setString(6, archivos.getResultado());

        ptmt.executeUpdate();

    } catch (SQLException e) {
         .......
    } finally {
            .....
    }

}

希望对你有帮助

【讨论】:

    【解决方案2】:

    在这个简单的例子中,我连接到一个数据库并创建一个语句,但我不使用 con.getConnection().createStatement 而是只使用 con.createStatement() 尝试这样做,这可能是问题所在。我将使用我已经拥有的 I 数据库的整个 sql Demo 留在这里,如果您将来有其他问题,它可能会有所帮助。如果您的问题仍然存在,请告诉我。

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "pc_control";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "";
        try {
            Class.forName(driver).newInstance();
            Connection conn = DriverManager.getConnection(url + dbName, userName, password);
            Statement st = conn.createStatement();
            ResultSet res = st.executeQuery("SELECT * FROM computers");
            while (res.next()) {
                int comp_id = res.getInt("computer_id");
                int emp_id = res.getInt("employee_id");
                String image = res.getString("image");
                String brand = res.getString("brand");
                String model = res.getString("model");
                String m_board = res.getString("m_board");
                String processor = res.getString("processor");
                int ram = res.getInt("ram");
                String hdd = res.getString("hdd");
                String os = res.getString("os");
                String ip_add = res.getString("ip_add");
    
    
                System.out.println(comp_id + "\t" + emp_id + "\t" + image + "\t" + brand + "\t" + 
                        model + "\t" + m_board + "\t" + processor + "\t" + ram + "\t" + hdd + "\t" 
                        + os + "\t" + ip_add + "\t");
            }//            
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    更新

    尝试以这种方式或类似的方式重新定义您的连接类。

    我希望这对你有帮助。很抱歉,我无法指出您的错误,但您的连接实现对我来说有点奇怪。

    public class MySqlConnection {
    
    static String url = "jdbc:mysql://localhost:3306/";
    static String dbName = "pc_control";
    static String driver = "com.mysql.jdbc.Driver";
    static String userName = "root";
    static String password = "";
    static Statement st;
    static Connection conn;
    
    public MySqlConnection() {
    }
    
    public static boolean connect() {
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, userName, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    
    public static ResultSet read(String query) 
    {
        ResultSet res = null;
        try {
            st = conn.createStatement();
            res = st.executeQuery(query);
        } catch (SQLException ex) {
            Logger.getLogger(MySqlConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return res;
    }
    
    }
    

    要进行查询,只需以这种方式调用任何其他类的方法:

    String query = "SELECT * FROM computers WHERE computer_id= " + id; //or whatever
    ResultSet res = MySqlConnection.read(query);
    

    【讨论】:

    • 谢谢,但很遗憾我无法删除 getConnection();。如果我这样做,则会出现错误,因为:“找不到符号符号:方法 createStatement() 位置:连接类型的变量 con ----:(
    猜你喜欢
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    相关资源
    最近更新 更多