我已经阅读了所有解决方案,但现在我不知道如何通过java jdbc保存文件路径到mysql。下面是我的代码:
enter try{
String url= "jdbc:mysql://127.0.0.1:3306/test";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con= DriverManager.getConnection(url,"root","");
System.out.println("ket noi thanh cong");
s = con.createStatement( );
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
fileName = f.getAbsolutePath().toString();
String input = "INSERT INTO imagesrc ( image_src ) VALUES (?);";
PreparedStatement p = con.prepareStatement(input);
p.setString(1, fileName);
System.out.println(p.toString());
p.executeQuery();
}
catch(Exception e){
System.out.println("error");
} here
但它不运行和错误?当我打印SQL代码时:
System.out.println(p.toString());
复制并粘贴到mysql是运行和没有错误?请帮帮我,谢谢。
谢谢salah,这就是这个问题的解决方案:
String url= "jdbc:mysql://127.0.0.1:3306/test";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con= DriverManager.getConnection(url,"root","");
System.out.println("ket noi thanh cong");
s = con.createStatement( );
JFileChooser chooser = new JFileChooser();
chooser.showOpenDialog(null);
File f = chooser.getSelectedFile();
fileName = f.getAbsolutePath();
String input = "INSERT INTO imagesrc ( image_src ) VALUES (?)";
PreparedStatement p = con.prepareStatement(input);
p.setString(1, fileName);
// s.executeUpdate(input);
p.executeUpdate();
需要使用executeUpdate()方法来执行INSERT语句,而需要使用executeQuery()方法来执行SELECT语句。这是由于JDBC规范对它们的用法施加了要求:
Statement.executeQuery()的Java API文档:
执行给定的SQL语句,返回单个ResultSet对象。
参数:
sql—要发送到数据库的sql语句,通常是静态sql SELECT语句
和来自Java API文档的Statement.executeUpdate():
执行给定的SQL语句,该SQL语句可以是INSERT、UPDATE或DELETE语句,也可以是不返回任何结果的SQL语句,例如SQL DDL语句。
参数:
sql - an sql数据操作语言(DML)语句,如INSERT, UPDATE或DELETE;或不返回任何值的SQL语句,如DDL语句。
查看更多详细信息