簡體   English   中英

在NetBeans中將SQL數據庫連接到JAVA時出現問題

[英]Trouble with connection SQL database to JAVA in NetBeans

我嘗試將netbeans與SQL連接,但是仍然有問題。 我想,仍然缺少一些東西。

在這里,我創建此類:(現在這里發生錯誤-另一方面,我真的不知道這是否完全正確)

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”);“

由於標簽的原因:“找不到符號symbol:method setString(int,String)位置:變量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);
    }

這樣,一切似乎都可以,但是當我運行一個項目時,出現錯誤並指向:“ statement = con.getConnection()。createStatement();”,程序當然會崩潰。

我真的不知道該怎么辦。

如果有人有想法,請寫下來。

非常感謝。

在這里的這個簡單示例中,我連接到數據庫並創建了一條語句,但是我不使用con.getConnection()。createStatement,而只是con.createStatement()嘗試這樣做可能是問題所在。 我將使用我已有的數據庫將整個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);

這是一個准備好的netbeans的例子

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 {
            .....
    }

}

希望對你有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM