I am using JTDS with Java to connect to a Microsoft SQL database. I am able to connect to the database perfectly. However when I run the code below, I am getting an error "Could not find stored procedure 'get_queue_items' ". I've tried prefixing 'dbo.' to the stored procedure name, however I continue to get the error. I've also included the actual stored procedure for reference.
try {
// Prepare and call the stored procedure
CallableStatement proc = connection.prepareCall("{call get_queue_items(?) }");
// Register the ResultSet
proc.registerOutParameter(1, java.sql.Types.INTEGER);
// Register Input Parameters
proc.setInt("#last_queue_entry", 1);
// Execute the stored procedure
proc.execute();
// If we have a ResultSet
if (proc.getMoreResults()) {
ResultSet rs = proc.getResultSet();
if (rs.next()) {
// to complete...
}
}
}
catch(Exception ex)
{
System.out.println("Error: " + ex.getMessage());
}
And the stored procedure:
USE [test]
GO
/****** Object: StoredProcedure [dbo].[get_queue_items] Script Date: 11/17/2011 11:43:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[get_queue_items] #qid int OUT, #last_queue_entry int as
-- select all the new records out of the main table into a temp table
-- the temp table is what we will use to process
select #qid = qid from test.[dbo].que_items
where qid > #last_queue_entry
I'm new to JTDS and Java, so its likely I am at fault, but any help would be appreciated.
Edit: Changed the Stored Procedure as per Cristian's advice, still getting the same error 'Could not find stored procedure 'get_queue_items'
Edit 2: Still not working - database connectivity seems fine also.
Today I met same problem and it seems to me that there is a bug in jTDS implementation. For me solution was procedure renaming and removing all underscore symbols (that is getQueueItems(?) in your case). Try, I think it must help to you.
you have to specify the output parameters, there are certain parameters that can not be specified as: text, ntext, and image.
ALTER procedure [dbo].[get_queue_items] #id int OUT, #last_queue_entry int as
-- select all the new records out of the main table into a temp table
-- the temp table is what we will use to process
select #id = id from test.[dbo].que_items
where qid > #last_queue_entry
this prodecure will return only id numbers
Related
I am primarily a Java developer with some level of oracle DB experience. I am having to use MSSQL server 2008 R2 for one project. I took a quick tutorial of mssql server on udemy and started creating functions and procedures.
The problem is three fold,
a) i need to pass a few values to a procedure or a function and insert them in a table and return.
i have read online that functions cannot be used for inserting into existing tables .. rather they only insert into temp tables.. is this true ? can you not insert into a table and return the row inserted in a function on MSSQL server? I used the below procedure anyways.
USE [KingsBayY]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter PROCEDURE test_fn_transaction_insert_log #receipt varchar(25), #amount varchar(25), #stdt varchar(25),
#enddt varchar(25)
AS
SET NOCOUNT ON
INSERT INTO [TransactionLog] ( TimeStamp, CashierID, Total,RecurringStartDate,
RecurringStopDate, CustomerID, ReceiptNumber, Voided, Attendee, ItemLookupCode)
SELECT CURRENT_TIMESTAMP AS [TimeStamp], tr.CashierID, #amount, #stdt,#enddt,c.ID,tr.ReceiptNumber,
tr.Voided,it.ItemLookupCode, tr.Comment
from [Transaction] tr, TransactionEntry trent, Item it, Customer c
where trent.TransactionID = tr.ID
and trent.ItemID = it.ID
and c.ID=tr.CustomerID
and tr.ReceiptNumber=#receipt
--condition to ensure no duplicates are entered and [TransactionLog].ID not in (select ID from [TransactionLog] where [TransactionLog].ID=tr.ID)
GO
As of now, When i try to call this procedure in Java as below, it throws an exception
public String saveTr(String a, String b, String c, String d) {
try
{
SqlServerConn conn = new SqlServerConn();
connect=conn.getConnection();
String SQL = String.format("Exec test_fn_transaction_insert_log ?,?,?,?");
pstmt = connect.prepareStatement(SQL);
pstmt.setString(1, a);
pstmt.setString(2, b);
pstmt.setString(3, c);
pstmt.setString(4, d);
pstmt.executeQuery();
}
catch (Exception e2)
{
e2.printStackTrace();
return "fail";
}
//ArrayList<Transactions> list=getrowFromResultSet2(rs);
return "success";
}
i get this exception:
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
b) in the above procedure, i need to return the row just inserted. how can i do this? or atleast get a return code?
c) is this even the best way of writing this procedure for the requirement? can functions be used ?
a) That's correct, functions, in the sense that SQL refers to them as, cannot be used to perform any data modification. However what youre looking for is a stored procedure. In the Java/C# lingo, a stored procedure is still basically a function, it's just distingished in SQL in terms of what it is or isnt allowed to perform.
b) If you need the row returned, you have two options. The first, since you're using SQL Server 2008 or more recent, you can use the OUTPUT clause. You can read about it on MSDN, but the idea is between your insert and the select, you just slide in an OUTPUT statement that takes the stuff you're currently inserting, and selects it out. Alternatively, if you dont want to use the output clause, you can, after your insert, just make a select statement which returns the values associated with the primary key(s) you just inserted
c) see a. Procedure is the way to go.
EDIT: link to MSDN OUTPUT documentation. Specifically look at how it works with inserts.
https://msdn.microsoft.com/en-us/library/ms177564.aspx
Here's a good article on the summary of function and procedure differences in SQL
http://www.dotnet-tricks.com/Tutorial/sqlserver/7EDL150912-Difference-between-Stored-Procedure-and-Function-in-SQL-Server.html
The problem statement is like this :
I have to create a procedure to fetch all the data (only 9 records actually) in Employees1 table and then display that data by calling this procedure in Java. I am working on a legacy application that is built on struts 1.3 but that should not be of any concern here i guess.
Below is the procedure I created:
CREATE OR REPLACE PROCEDURE getALLEmployees(ref_cur out sys_refcursor)
IS
BEGIN
OPEN ref_cur FOR 'SELECT * FROM employees1';
END;
And here is my Java Code:
callableStatement = conn.prepareCall("{call getAllEmployees()}");
// Below line is (EmployeeDataJdbc.java:33) as mentioned in error
callableStatement.registerOutParameter(1,oracle.jdbc.driver.OracleTypes.CURSOR);
boolean isResultSet = callableStatement.execute();
rs = (ResultSet)callableStatement.getObject(1);
/*Employee paramater Order in DB
employee_id, employee_first_name, employee_last_name, employee_address,
employee_blood_group, employee_email, employee_department, employee_role,
employee_band, employee_mobile_number*/
while(rs.next()){
emp.setEmployeeId(rs.getInt(1));
emp.setEmployeeFirstName(rs.getString(2));
emp.setEmployeeLastName(rs.getString(3));
emp.setEmployeeAddress(rs.getString(4));
emp.setEmployeeBloodGroup(rs.getString(5));
emp.setEmployeeEmail(rs.getString(6));
emp.setEmployeeDepartment(rs.getString(7));
emp.setEmployeeRole(rs.getString(8));
emp.setEmployeeBand(rs.getString(9));
emp.setEmployeeMobileNumber(rs.getLong(10));
employeeList.add(emp);
}
This is the error I am getting at console:
Connected to Database
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:121)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:268)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:348)
at jdbcHandles.EmployeeDataJdbc.getEmployeeList(EmployeeDataJdbc.java:33)
I have not used PL-SQL since a long long time. Please help me find out where I am going wrong. Thanks in advance.
Note: I am using Oracle 10G express edition as database.
callableStatement = conn.prepareCall("{call getAllEmployees(?)}");
You have to mention where the out parameter has to be binded using the ?
And since the column count can change. Better have a check using the Metdatadata call rSet.getColumnCount()
I am working on the web application project developed using java. In my working project,
i have the requirement like i need to create the database dynamically after the user has been registered.I had done that approach.
But, now i want to call one stored procedure that is available in another schema(Master DB).The stored procedures contains tables. Now, i want to call that procedure in dynamically created DB.
I have written the code like following, can anybody help me to know what's wrong in this code,
Connection c1 = DriverManager.getConnection(URL, USER, PASSWORD);
java.sql.CallableStatement cstmt=null;
System.out.println("Invoking the stored procedure from subscription DB........");
String callSP="{call masterdb.createCorporateDBProc()};";
cstmt= c1.prepareCall(callSP);
cstmt.execute();
java.sql.CallableStatement cstmt=null;
try {
System.out.println("Invoking the stored procedure from subscription DB........");
String callSP="{call subscription.createCorporateDBProc()}";
cstmt = c1.prepareCall(callSP);
int r = cstmt.executeUpdate();
System.out.println("SP created"+r);
System.out.println("SP invoked and executed successfully in corporate DB....");
} catch(com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException e){
e.printStackTrace();
cstmt.close();
c1.close();
}
See javadoc for Statement:
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html#executeUpdate%28java.lang.String%29
Returns:
either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
This means that execute for procedure will return 0. Check your database as well, if the call was successful.
I'm using postgresql to host my database. In my database, I have a table say xyz whose structure is as shown below
id content folder
1 hello Inbox
2 hi Sent
I want to export this table to CSV using my java program. The code snippet is below
Connection connection2 = new ServerDBConnect().getConnection();
PreparedStatement statement = connection2.prepareStatement("copy (SELECT * FROM xyz WHERE folder=? ) to 'C:/export.csv' delimiter ','");
statement.setString(1, FOLDER_SELECTED); //Here, FOLDER_SELECTED=Inbox
statement.execute();
When I execute this code, I'm getting SQLException saying
ERROR: there is no parameter $1
If I execute the code without folder specified ("copy (SELECT * FROM xyz) to 'C:/export.csv' delimiter ','")), the code works fine.
What am I doing wrong here? How to go about this problem?
Note: If I execute the query (copy (SELECT * FROM xyz WHERE folder='Inbox' ORDER BY time) to 'G:/export.csv' delimiter ',') directly in the Postgresql SQL console, I'm getting the desired output.
Please help
Ah
I finally found the answer myself.
Small change in the query gave me the desired result
The query is suppose to be like this
Connection connection2 = new ServerDBConnect().getConnection();
PreparedStatement statement = connection2.prepareStatement("copy (SELECT * FROM xyz WHERE folder='" + FOLDER_SELECTED + "' ) to 'C:/export.csv' delimiter ','");
This was driving me crazy, but finally done :-)
I am trying to use a Java application (which I do not have the source code for) to output the results of a call to a stored procedure into a text file.
This file works for other similar stored procedures in the system, but I can't seem to get it to produce anything for my new text file other than this exception:
ResultSet is from UPDATE: No Data
I've simplified the body of the stored procedure to a simple select 'Hello World!' and even that doesn't seem to be able to be written out.
Is there anything I can do within the stored procedure to produce results in a fashion that Java will accept?
I encountered this java.sql.SQLException. In my case I was running a query in this way:
String query =
"-- a classical comment " +
"select * " +
"from MYTABLE ";
ResultSet rs = conMain.createStatement().executeQuery(query);
while(rs.next()) {
//do something...
}
rs.next() throws the exception. The reason is that, due to the comments, query results to be:
"-- a classical comment select * from MYTABLE "
hence it's all commented... query is invalid! Many examples could be shown with this mistake (with the comment in the middle of the query etc.).
Solutions: add a \n at the end of each line of the query or use comments in the /*...*/ form.
I selected an older version of the driver an it worked for me.
http://dev.mysql.com/downloads/mirror.php?id=13598 (mysql-connector-java-5.0.8.zip)