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.
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
Searching the web for a solution to create a database for my spring project when it doesn't exist, I found this topic here in stackoverflow:
Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?
with this stored procedure to acomplish that:
DO
$do$
BEGIN
IF EXISTS (SELECT 1 FROM pg_database WHERE datname = 'mydb') THEN
RAISE NOTICE 'Database already exists';
ELSE
PERFORM dblink_exec('dbname=' || current_database() -- current db
, $$CREATE DATABASE mydb$$);
END IF;
END
$do$
I want run this procedure from my Java code. My initial idea was include this code as a String atribute in this Service class:
#Service
public class InstallService {
private String query = "";
public boolean create_database(String maquina, String usuario, String senha) {
return false;
}
public boolean create_user(String usuario, String senha, String email) {
return false;
}
}
But I just find out this can't be done. Anyone have any sugestion of how to do that inside this class?
I would recommend calling the stored procedure via whatever method you're currently using to connect to Postgres from Spring. (i.e. Spring JDBC: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/jdbc.html; or perhaps MyBatis, etc.)
You could define the stored procedure in, say, the template database, and then connect to it via Spring JDBC or whatever method you're employing, with a query of the form:
SELECT stored_proc_name(dbname)
(You would need to have the stored procedure take the DB name as an argument, also.)
Edit:
In response to the comment below, inquiring if this can be done without adding anything to a database, the answer is yes:
You could connect to the template1 DB, run the SELECT query against pg_catalog to see if the DB exists (you'll get an empty set back if it doesn't), and if it doesn't exist, run another query on the connection to the template1 db to create the DB.
Basically, it'd be deconstructing the stored procedure into its constituent parts and calling them directly from Java using JDBC or similar.
I am trying to connect to a SQL Server database, but I don't really know how to go about it using the info I was given. I was given the following:
Provider
DataSource
Persist Security Info
User ID
Initial Catalog
I have always connected via a web address or something, so I didn't really know how to go about using this. I am attempting to do this is Java using JDBC.
See here a wide list of examples, depending on which version you're using:
SQL Server 2000
SQL Server 2005
SQL Server 2008
To connect to MSSQL Server from a Java application, you need to use the JDBC API. The JDBC API provides classes and methods that connect to the database, load the appropriate driver, send SQL queries, retrieve results etc.
HOW TO CONNECT TO THE DATABASE: A ‘Connection’ object represents a connection with a database. To establish the connection, use the method ‘DriverManager.getConnection’. This method takes a string containing a URL which represents the database we are trying to connect to. Below is the sample code for establishing a connection:
private String DATABASE_URL = "jdbc:odbc:embedded_sql_app"; // establish connection to database
Connection connection = DriverManager.getConnection( DATABASE_URL,"sa","123" );
Detailed discussion about the Database URL and how to create it can be found in the resource provided at the end of this post.
QUERYING THE DATABASE: The JDBC API provides three interfaces for sending SQL statements to the database, and corresponding methods in the ‘Connection’ interface create instances of them. 1. Statement - created by the ‘Connection.createStatement’ methods. A ‘Statement’ object is used for sending SQL statements with no parameters.
2. PreparedStatement - created by the ‘Connection.prepareStatement methods’. A ‘PreparedStatement’ object is used for precompiled SQL statements. These can take one or more parameters as input arguments (IN parameters).
3. CallableStatement - created by the ‘Connection.prepareCall’ methods. ‘CallableStatement’ objects are used to execute SQL stored procedures from Java database applications.
RETRIEVING THE RESULT: A ‘ResultSet ‘is a Java object that contains the results of executing a SQL query. The data stored in a ‘ResultSet’ object is retrieved through a set of get methods that allows access to the various columns of the current row. The ‘ResultSet.next’ method is used to move to the next row of the ‘ResultSet’, making it the current row. The following code fragment executes a query that returns a collection of rows, with column ‘a’ as an ‘int’, column ‘b’ as a ‘String’, and column ‘c’ as a ‘float’:
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) { // retrieve and print the values for the current row
int i = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
System.out.println("ROW = " + i + " " + s + " " + f);
}
This is just a brief introduction on how to interact with a database from Java. For more details on the items discussed above as well as information on passing parameters, executing stored procedures etc. please refer to the following resource: ( http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html#Shahriar_N_Embedding_SQL_in_Java ) Here, you will also find information on how to interact with a database programmatically; i.e. without using SQL. Hope you find this useful.
Source:
http://www.shahriarnk.com/Shahriar-N-K-Research-Embedding-SQL-in-C-Sharp-Java.html
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
I have a MSSQL Database, and I have a stored procedure for any possible query, most of them just return a row of data with 3 columns or just execute an INSERT
How in java to connect to the DB and execute a stored procedure, and retrieve some data ?
A connection pool like DBCP makes a big difference. The connection time can be save this way.
Prepared statements can help the database to skip query parsing. The parsed statements will be cached.
Batch updates help when you're executing a statement repeatedly.
Setting the right fetch size is another optimization for queries.
Use the MSSQL JDBC Driver to create a connection to the database
In jdbc, you need to create a CallableStatement to execute the procedure. It's like this:
.
CallableStatement callable = null;
try {
String sqlCommand = "{call yourProcNameHere (?, ? /* ... */)}";
callable = conn.prepareCall(sqlCommand);
// ...
}
catch (SQLException e) {
// ...
}
finally {
/ ...
}
By reading and working through a JDBC Tutorial.