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