I have created an API module of spring boot application to call stored procedure. When it comes to the implementation, stmt.execute cannot be called with no response. Would you please tell me which module or wayout to modify under my java environment is 1.8?
int retVal = -1;
int errCode = -1;
String errText = null;
int outPos;
int pos = 0;
System.out.println("call 2");
String SQL_SELECT = "{call database_sid.test_pkg.get_pc_lue(?,?,?,?,?,?)}";
try (Connection conn = DriverManager.getConnection(DBC_URL, USERNAME, PASSWORD);
CallableStatement preparedStatement = conn.prepareCall(SQL_SELECT);
) {
System.out.println("call db");
preparedStatement.setString(++pos, "OFFER_TYPE");
preparedStatement.setString(++pos, null); // acct srv limit
preparedStatement.registerOutParameter(outPos = ++pos, Types.REF_CURSOR);
preparedStatement.registerOutParameter(++pos, Types.INTEGER);
preparedStatement.registerOutParameter(++pos, Types.INTEGER);
preparedStatement.registerOutParameter(++pos, Types.VARCHAR);
System.out.println("call 10");
ResultSet resultSet = preparedStatement.executeQuery();
System.out.println("call 11");
while (resultSet.next()) {
String value = resultSet.getString("LOOKUP_VALUE");
String type = resultSet.getString("LOOKUP_TYPE");
PcTblBPcLookUp obj = new PcTblBPcLookUp();
obj.setLookUpValue(value);
obj.setLookUpType(type);
result.add(obj);
System.out.println("call 1obecj1");
}
result.forEach(x -> System.out.println(x));
System.out.println("call finish ");
} catch (SQLException e) {
System.err.format("SQL State: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
System.out.println("call error : " + e.getMessage());
}
You need to execute your stored procedure using execute and then you need to fetch your resultset from opsition registered for out parameter
preparedStatement.execute();
ResultSet rs = (ResultSet) preparedStatement.getObject(outPos);
Related
i'm a new programmer, I was given a task to create a class Subject.java, in which it'll ask the students how many subjects they're taking and then store the subjects information into the database, but the problem with my current code is that only one row is updated in the database. My code is as the following, please help me.
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i=0;
for (i=0; i<sub; i++)
{
System.out.print("\nCode: ");
this.setCode(in.next());
System.out.print("\nName: ");
this.setName(in.next());
System.out.print("\nCredit: ");
this.setCredit(in.nextInt());
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
try (Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);)
{
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt (3, this.getCredit());
pstmt.addBatch();
if (pstmt.executeUpdate() == 1)
{
System.out.println("\nNew subject has been created succesfully!");
}
else
{
System.out.println("\nError");
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
}
As Nexevis said , you need to put your Connection code outside your for-loop like below :
// insert into database
ResultSet rs = null;
String sqlInsert = "INSERT INTO subject (code, name, credit) VALUES (?,?,?)";
System.out.print("\nEnter number of subject: ");
int sub = in.nextInt();
int i = 0;
try {
Connection conn = MySQLDB.getConnection();
PreparedStatement pstmt
= conn.prepareStatement(sqlInsert);
for (i = 0; i < sub; i++) {
System.out.print("\nCode: ");
this.setCode( in.next());
System.out.print("\nName: ");
this.setName( in.next());
System.out.print("\nCredit: ");
this.setCredit( in.nextInt());
// assign parameters for statement
pstmt.setString(1, this.getCode());
pstmt.setString(2, this.getName());
pstmt.setInt(3, this.getCredit());
pstmt.addBatch();
}
try {
// execute it to insert the data
pstmt.executeBatch();
} catch (SQLException e) {
System.out.println("Error message: " + e.getMessage());
return; // Exit if there was an error
}
pstmt.close();
conn.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html
I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
gurus,
I am new to Java SQL, and need some help.
I'm trying to get a parameter from MS SQL Server 2008. The data is definitely there - it is a current and valid DB, and I'm trying to use the users records to get cridentials for another application.
I asserted the following query:
String query = "SELECT [USER].qc_number FROM [USER] WHERE "[USER].login_name = '"
+ userNameInput + "' AND [USER].password = '" + passWordInput + "';";
Where userNameInput and passWordInput are received from the user. The URL, query and driver class are definitely correct: I checked the DB schema both from the application and from the server views. Furthermore, I verified all the Exceptions systems by changing parameters one by one, resulting in correct Exceptions messages. However, I get a resultSet with 1 column and 0 rows.
The code is below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class trOdbc
{// database URL
final String DB_URL = "***";
final String Class_URL = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private Connection connection = null; // manages connection
private Statement statement = null; // query statement
private ResultSet resultSet = null; // manages results
private Boolean connectedToDatabase = false;
// ----------------------------------------------------------
public void createJdbcConnection()
{ // connect to database books and query database
if (connectedToDatabase)
{ return; }
try
{ // connectedToDatabase is false - establish the connection
Class.forName(Class_URL);
connection = DriverManager.getConnection
(DB_URL, "***", "***" );
statement = connection.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
connectedToDatabase = true;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection establishment: " + ex); }
catch (ClassNotFoundException ex)
{ System.out.println ("Class not found exception in query process: " + ex); }
}
// ----------------------------------------------------------
public String [][] processJdbcQuery (String query)
{
createJdbcConnection ();
if (!connectedToDatabase)
{ return null; }// the connection wasn't established
try
{// query database
resultSet = statement.executeQuery(query);
int columns = resultSet.getMetaData().getColumnCount();
int rows = 0;
if (resultSet != null)
{
resultSet.beforeFirst();
resultSet.last();
rows = resultSet.getRow();
}
String [][] tempData = new String[rows][columns];
resultSet.beforeFirst();
rows = 0;
while (resultSet.next())
{
for (int x = 1; x <= columns; x++)
{
tempData [rows][x - 1] = resultSet.getString (x);
}
rows++;
}
CloseJdbcConnection ();
return tempData;
}
catch (SQLException ex)
{
System.out.println ("SQL Exception in query process: " + ex);
CloseJdbcConnection ();
return null;
}
} // end processJdbcQuery
// ----------------------------------------------------------
public void CloseJdbcConnection()
{
if ( connectedToDatabase )
{// close Statement and Connection. resultSet is closed automatically.
try
{
statement.close();
connection.close();
connectedToDatabase = false;
}
catch (SQLException ex)
{ System.out.println ("SQL Exception in connection closure: " + ex); }
} // end if
} // end method CloseJdbcConnection
} // end class trOdbc
Why don't you use Prepared Statement instead ?
Here is a good tutorial for using prepared statement in java
In your case it would be :
String query = "SELECT [USER].qc_number FROM [USER] " +
"WHERE [USER].login_name = ? AND [USER].password = ?;";
And then set it with different values each time you execute it like :
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, userNameInput);
ps.setString(2, passWordInput);
resultSet = ps.executeQuery();
Below is a generic class I wrote that calls a stored procedure on the server:
public class StoredProc {
Connection con = null;
ResultSet rs = null;
CallableStatement cs = null;
public StoredProc(String jdbcResource, String storedProcName){
this(jdbcResource, storedProcName, new String[0], new String[0]);
}
public StoredProc(String jdbcResource, String storedProcName, String[] params,String[] paramTypes){
Connection con = new databaseConnection(jdbcResource).getConnection();
//Get length of parameters and sets stored procs params (?, ?, ...etc)
String procParams = "";
int paramSize = params.length;
if(paramSize != 0){
for(int i = 0; i < paramSize; i++){
if(i == paramSize){
procParams += "?";
}else{
procParams += "?, ";
}
}
}
try{
CallableStatement cs = this.con.prepareCall("{?=call "+storedProcName+" ("+procParams+")}");
for(int j = 0; j < params.length; j++){
if (paramTypes[j].equalsIgnoreCase("Int")) {
int x = 0;
try{
x = Integer.parseInt(params[j]);
} catch(Exception e) {}
cs.setInt(j, x);
} else if (paramTypes[j].equalsIgnoreCase("Boolean")) {
boolean x = false;
try{
x = (params[j].equalsIgnoreCase("True")) || (params[j].equalsIgnoreCase("T")) || (params[j].equalsIgnoreCase("1")) || (params[j].equalsIgnoreCase("Yes")) || (params[j].equalsIgnoreCase("Y"));
} catch(Exception e) {}
cs.setBoolean(j, x);
} else if (paramTypes[j].equalsIgnoreCase("String")) {
cs.setString(j, params[j]);
}
}
}catch(Exception e){
System.out.println("---------------------------------------------");
System.out.println("Problem constructing callableStatement: "+e);
System.out.println("---------------------------------------------");
}
}
public ResultSet runQuery(){
try{
rs = cs.executeQuery();
}catch(SQLException e){
System.out.println("---------------------------------------------");
System.out.println("Problem executing stored procedure: "+e);
System.out.println("---------------------------------------------");
}
return rs;
}
public void runUpdate(){
try{
cs.executeUpdate();
}catch(SQLException e){
System.out.println("---------------------------------------------");
System.out.println("Problem executing stored procedure: "+e);
System.out.println("---------------------------------------------");
}
}
} //end of class
for some reason I'm getting a NullPointerException on the line I'm trying to construct a CallableStatement --> CallableStatement cs = this.con.prepareCall("{?=call "+storedProcName+" ("+procParams+")}");
The callable statement should look like this at run time:
cs = this.con.prepareCall({?=call getUnlinkedDirectdeposits()});
The stored proc is called this in the database: [dbo].[getUnlinkedDirectdeposits]
Any help would be appreciated!
Thanks in advance,
You are using the wrong "con" variable. In your method you're initialising a variable (local to the method) called con:
Connection con = new databaseConnection(jdbcResource).getConnection();
But then you use this.con, which is the con field of the StoredProc object you're currently executing in. Since it was never initialised, you get a NullPointerException.
Your Connection field is null!
You create a new Connection instance in StoredProc instead of assigning it to the field con of your class. But when trying to created the CallableStatement your are using the this.con which has not been set before.