How to execute a procedure with JDBC - java

This is my function :
public static void execute_delete_on_db(String pass, String login, String port,
String host, String table_name, String file_path) throws Exception {
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#//"
+ host + ":" + port + "/xe", login, pass);
PreparedStatement statement = null;
Statement stmt = null;
String query = "delete from AA_ALL";
stmt = conn.createStatement();
stmt.executeQuery(query);
sql_statement.close();
conn.commit();
conn.close();
}
At least this is the most important part of my function. Above code works fine. I tried to execute my procedure by calling this sql statement :
EXECUTE delete_all_rows_from_table('all');
In Java it looked like this :
String query = "EXECUTE delete_all_rows_from_table('all')";
On the database it is working fine, but in Java this is giving me the error.
Can you tell me what am I doing wrong?

You can call your procedure and not execute it like so :
String query = "{call delete_all_rows_from_table(?)}";
CallableStatement statement = connection.prepareCall(query);
statement.setString(1, "all");
statement.execute();
You can learn more here : JDBC CallableStatement – Stored Procedure OUT parameter example and JDBC Stored Procedure

Notice if the procedure got some out parameters, you would have to register the parameters.
Here is an example, assuming we already import the modules (java.sql.CallableStatement and java.sql.Types) and the connection has been established.
CallableStatement callStmt = conn.prepareCall("{CALL <PROCEDURE_NAME>(?, ?, ?)}");
callStmt.setString(1, data);
callStmt.registerOutParameter(2, Types.VARCHAR);
callStmt.registerOutParameter(3, Types.VARCHAR);
callStmt.executeQuery();
String outParameter1 = callStmt.getString(2);
String outParamenter2 = callStmt.getString(3);

Related

MySQL Java prepared statement Syntax error

I need to select rows from mysql table based on various criteria, for example Colour= Black, or size= L.
The code works without the preparedstatement and the question marks, but whenever I attempt to use the question marks the code does not run.
I have read something about typing the question mark like \'?'// but I am not sure about the exact format.
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
Statement stmt = con.createStatement();
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
ResultSet rs = stmt.executeQuery(sql);
PreparedStatement preparedStmt = con.prepareStatement(sql);
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
Also, Size is written out in orange colour, but the error happens also when I only use this sql String
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ?;";
I have looked at like 20 different answers, but didnt find anything helpful, so thanks in advance for any help!
You are executing the query using a normal java.sql.Statement, not using a java.sql.PreparedStatement. This won't work because a normal Statement does not support parameterized queries. So, remove the creation and execution of the Statement, and make sure you execute the statement using the PreparedStatement:
String URL = "jdbc:mysql://localhost:3306/clothing";
String USERNAME = "root";
String PASSWORD = "password";
String sql= "SELECT * FROM clothing.Lostandfound WHERE Colour = ? AND Size = ?;";
try (Connection con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement preparedStmt = con.prepareStatement(sql)) {
preparedStmt.setString(1, Data1);
preparedStmt.setString(2, Data2);
try (ResultSet rs = preparedStmt.executeQuery()) {
// process result set
}
}
Also note the addition of try-with-resources, which will ensure connections, statements and result sets are closed correctly.

Error in sql query to fetch data from wamp server [duplicate]

I had tried several times using prepared statements but it returns SQL exception. here is my code:
public ArrayList<String> name(String mobile, String password) {
ArrayList<String> getdata = new ArrayList<String>();
PreparedStatement stmt = null;
try {
String login = "select mobile, password from tbl_1 join tbl_2 on tbl_1.fk_id=2.Pk_ID where mobile=? and password=?";
String data = "select * from tbl_2 where password='" + password + "'";
PreparedStatement preparedStatement = conn.prepareStatement(login);
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
ResultSet rs = preparedStatement.executeQuery(login);
Statement stmts = (Statement) conn.createStatement();
if (rs.next()) {
System.out.println("Db inside RS");
ResultSet data = stmts.executeQuery(data);
while (data.next()) { /* looping through the resultset */
getdata.add(data.getString("name"));
getdata.add(data.getString("place"));
getdata.add(data.getString("age"));
getdata.add(data.getString("job"));
}
}
} catch (Exception e) {
System.out.println(e);
}
return getdata;
}
While running this, I got the following SQL exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 '? and password=?' at line 1.
Any suggestion to make this work?
any piece of code is appreciated.
You need to use:
preparedStatement.executeQuery();
instead of
preparedStatement.executeQuery(login);
when you pass in a string to executeQuery() that query is executed literally and thus the ? is send to the database which then creates the error. By passing query string you are not execution the "cached" prepared statement for which you passed the values.
For both parameter you use preparedStatement.setString(1, ..); so the first parameter is set two times. but you never set the value for second parameter.
so change
preparedStatement.setString(1, mobile);
preparedStatement.setString(1, password);
to
preparedStatement.setString(1, mobile);
preparedStatement.setString(2, password);

stored procedure is not displaying results in jsp

I am trying to execute results from my stored procedure and it is not displaying anything. I have played around with sql syntax query and nothing worked...when I do a normal select statement I get results from my tables, but so far nothing worked with my stored procedure...what am I not getting results ?
I am using sql-server by the way
<%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://....";
String username = "something";
String password = "something";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs;
CallableStatement cs;
cs = conn.prepareCall("{ exec rptGetAssetbyLocation(?, ?,?,?,?,?) }");
cs.setString(1, "name");
cs.setString(2, "model");
cs.setString(3, "serialNumber");
cs.setString(4, "type");
cs.setString(5, "condition");
cs.setString(6, "note");
try {
cs.execute();
out.println("Stored procedure completed successfully.<br>");
} catch (Exception e) {
out.println("The following error occurred: " + e + "<br>");
}
%>
edit:
ran a stacktrace
I am getting an error com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '{'.
To display the output from the procedure to need to do something like this
char val= ((OracleCallableStatement)cs).getCHAR(3)
Remember OracleCallableStatement is an interface which implements CallableStatement, OraclePreparedStatement
You can override its method to get the results from the callable statments
Also these examples would help you
1.how to display tabledata with java stored procedure
2.Stored procedure with Input/Output parms and a ResultSet
3.Java Stored procedures
Hope this helps !!

How do I execute a stored procedure without parameters in JDBC?

I'm trying to execute a stored procedure without input variables like :
String sql2 = "{call vivek}" ;
System.out.println(sql2);
System.out.println("Executing procedure without parameters");
stmt = conn.createStatement();
stmt.executeQuery(sql2);
But its throwing an error saying :
syntax error at or near "{"
Position: 1
I'm trying to google it but not able to find anything. How do I do it ? By the way it didn't work with callablestatement also
Not tested:
CallableStatement cs = null;
cs = conn.prepareCall("{call vivek}");
cs.executeQuery();
http://docs.oracle.com/javase/tutorial/jdbc/basics/storedprocedures.html
It's similar to calling a function without arguments.
CallableStatement cat = null;
con = YourConnectionClass.getConnection();
cst = con.prepareCall("{call YOUR_PROCEDURE_NAME()}");
cst.executeQuery();
Could not find stored procedure? I will explain what it means when you get this error. Assuming our code is like this:
String sp="{call GetUnitReferenceMap}";
stmt=conn.prepareCall(sp);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
currencyMap.put(rs.getString(1).trim(), rs.getString(2).trim());
I have 4 DBs (sample1, sample2, sample3), but stmt will search location master (Default DB) then we will get an Exception.
We should provide DB name, then problem will be resolved::
String sp="{call sample1..GetUnitReferenceMap}";
Thanks for the help everyone but the following code worked for me :
sql2 += "{exec "+ proc_name2 +"}" ;
cstmt = conn.prepareCall(sql2);
cstmt.executeUpdate();
Here cstmt is the CallableStatement object by the way. And I'm using Postgresql Database hence the above code worked for me

getting out parameter from mysql stored procedure in java

I am having problem retrieving OUT parameter from mysql stored procedure in java.
CALL proc_after_topic_add('newtest',#result);
SELECT #result;
this query gives me desired out parameter but how would i retrieve it in java.I tried using CallableStatement but i get
java.sql.SQLException: Callable statments not supported.
error.Please guys help me.
I have tried following
String sql = "CALL proc_after_topic_add(?,?);";
CallableStatement cstmt = conn.prepareCall(sql);
cstmt.setString(1, topicname);
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
if (rs.getInt(1) == 1) {
res = 0;
} else {
res = -1;
}
}
I havent posted stored procedure code because there is nothing wrong with it.
PS:I a using mysql 5.5.21 and yes i should probably mention i am using mysql connector 3.0.15
Okay this is solved.For anyone who encounters the same problem,just download latest version of mysql connector.
Error in this line
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
change like this
String sql = "CALL proc_after_topic_add(?,?);";
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
Create a schema test and create a table employee in schema with 2 columns.
id and employeename and insert some data.
Use this Stored Procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_count_name1` $$
CREATE PROCEDURE `test`.`get_count_name1`(IN the_name VARCHAR(64),OUT
the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count from employee where employeename=the_name;
END$$
DELIMITER ;
Use this example.
username and password are root and root for me. change as per your
requirement. Here i am counting the occurence of employeename="deepak"
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/test";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call get_count_name1 (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
String name = "Deepak";
stmt.setString(1, name); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.INTEGER);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
int count=stmt.getInt(2);
System.out.println(count);
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Categories

Resources