0
Connection conn = getDBConnection(); //MYSQL CONNECTION. 
conn.prepareStatement("use testspl").execute();
conn.prepareStatement("SOURCE c:\Test.sql").execute()

Is this right way to fire a queries in mysql?

I tried but its not working, I'm getting the error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SOURCE C:\New.sql'"

Can someone help me figure out where I've gone wrong?

1
  • 1
    Do indent the code (4 spaces or more). Don't indent the text. Otherwise all hell breaks loose. Commented Dec 30, 2011 at 10:52

3 Answers 3

4

JDBC doesn't work like that: It handles only pure SQL - not mysql command prompt "utility" commands like you are trying to execute.

Problem with the first command:

The choice of database should be part of the connection properties in getDBConnection(); your connection should already be to the database you want.

Problem with the second command:

"SOURCE somefile.sql" is not valid SQL - it's mysql-only "funk".
Try reading the contents of the file c:\Test.sql then passing that as a String to prepareStatement()

You might want to try using apache commons IO FileUtils.readFileToString() to read the file in - it's a breeze to use

Sign up to request clarification or add additional context in comments.

Comments

0

I think you are looking for how to execute MySql query using Java

Code:

Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/Database_Name", "UserName", "Password");

Statement statement = con.createStatement();
String query = "Select * from table"
ResultSet result = statement.executeQuery(query)

Now read result object using while loop and extract your desired result from it. You can also use Prepared statements to execute query but the baisc logic remains same.

Take a look here Prepared Statements

Comments

0

As your error message states:

You have an error in your SQL syntax

Have a look in in the API:

public PreparedStatement prepareStatement(String sql) throws SQLException
Parameters:
sql - an SQL statement that may contain one or more '?' IN parameter placeholders

So the method takes a String Parameter and expect it to be a SQL statement but you pass it the path to an sql file. The Compiler is not that 'smart' to understand you want read the content of this file as the statement but takes the String is SQL syntax, pass it along and choke when it's not working :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.