Reputation: 871
I have read all solution but now i haven't know how to save a file path to mysql by java jdbc. Here is my code :
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
but is doesn't run and error ? when I print the SQL code by :
System.out.println(p.toString());
copy and paste that to mysql is was run and no error ? please help me,thank you
thank you salah anh this is the solution for this:
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();
Upvotes: 0
Views: 3664
Reputation: 8657
You will need to use the executeUpdate() method to execute the INSERT statement, while you'll need to use the executeQuery() method to execute the SELECT statement. This is due to the requirements imposed by the JDBC specification on their usages:
From the Java API documentation for Statement.executeQuery():
Executes the given SQL statement, which returns a single ResultSet object.
Parameters:
sql - an SQL statement to be sent to the database, typically a static SQL SELECT statement
and from the Java API documentation for Statement.executeUpdate():
Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.
Parameters:
sql - an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
For more details
Upvotes: 2