想要访问另一个类

时间:2016-02-28 07:30:03

标签: java

在这里,我在一个类中返回连接并尝试访问另一个类中的连接对象,其中我正在编写我准备好的语句来执行查询并更新表。请提示是否是正确的方法,如果不发布你的咨询。 在此先感谢

连接类

public class dbConnection {

    public Connection dbconnect()
    {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String db = "gup";
        String driver = "com.mysql.jdbc.Driver";
        String user = "root";
        String pass = "";
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url + db, user, pass);
            if(conn == null){
                System.out.println("Connection is not established");
            }
            return conn ;
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
        return null ;
    }

}

准备语句类以插入数据

public class InsertingData {


    public void insertfile(String fpath,String fname,String fext)
    {
        PreparedStatement pstmt = null;
        // Connection conn = null ;
        dbConnection dbcon = new dbConnection();
        pstmt = (PreparedStatement) dbcon.dbconnect();
        //Create the statement object
        String sql = "insert into FileDetails (folder_path,file_name,file_extension)" + "values (?,?,?)";
        try
        {

        //ResultSet rs = pstmt.executeQuery(sql);
        pstmt.setString(1, fpath);
        pstmt.setString(2, fname);
        pstmt.setString(3, fext);
        pstmt.executeQuery(sql);
        }
        catch(SQLException se)
        {
            System.out.println(se);
        }
    }
} 

1 个答案:

答案 0 :(得分:0)

使用Connection获取预准备语句,而不是尝试将Connection强制转换为PreparedStatement。取代

pstmt = (PreparedStatement) dbcon.dbconnect();
String sql = "insert into FileDetails (folder_path,file_name,file_extension)" + "values (?,?,?)";
....
pstmt.executeQuery(sql);

Connection conn = dbcon.dbconnect();
pstmt = conn.prepareStatement("insert into FileDetails (folder_path,file_name,file_extension)" + "values (?,?,?)");
....
pstmt.executeUpdate();

另见https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html