Stored Procedure in H2 Database - java

I am new to database and recently started writing test cases for H2 database.
I want to know how to test a stored procedure in Eclipse. I have seen the following:
http://www.h2database.com/html/features.html#user_defined_functions
How to CREATE PROCEDURE in H2
The sample code given in the h2database link,
"CREATE ALIAS NEXT_PRIME AS $$
String nextPrime(String value) {
return new BigInteger(value).nextProbablePrime().toString();
}
$$;
"
Where should this be declared?and how to run it?
PS - I have the H2 JAR file and am testing it.
If someone can tell me how to write a simple stored procedure in Java for H2, it would be of great help.
Also is there any equivalent of the following in H2?
"begin dbms_output" ?
Thanks.

There is no stored procedure and sql userdefined function in H2 database instead of that we use java methods and create a alias to refer that.We can call that methods using alias.
Below is a simple example:**
DROP ALIAS IF EXISTS MYFUNCTION;
CREATE ALIAS MYFUNCTION AS $$
String getTableContent(java.sql.Connection con) throws Exception {
String resultValue=null;
java.sql.ResultSet rs = con.createStatement().executeQuery(
" SELECT * FROM TABLE_NAME");
while(rs.next())
{
resultValue=rs.getString(1);
}
return resultValue;
}
$$;

You may have overlooked the examples in src/test/org/h2/samples/Function.java. Here's a related example:
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE ALIAS getVersion FOR \"org.h2.engine.Constants.getVersion\"");
ResultSet rs;
rs = st.executeQuery("CALL getVersion()");
if (rs.next()) System.out.println("Version: " + rs.getString(1));
Console: Version: 1.4.191
Addendum: The feature is not limited to functions; aliased methods can execute arbitrary Java code. For example, the query() method defined in Function.java may be aliased and called as shown below:
Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
Statement st = conn.createStatement();
st.execute("CREATE ALIAS query FOR \"cli.Function.query\"");
rs = st.executeQuery("CALL query('SELECT NAME FROM INFORMATION_SCHEMA.USERS')");
while (rs.next()) {
System.out.println("User: " + rs.getString(1));
}
Console: User: SA
Note that cli.Function.query is a copy of org.h2.samples.Function.query.

Below is the way we used to implemented in our project. It might be helpful :)
package com.procedures;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class CRITICAL_ACTIONS {
public static final int SAVE_ACTION(Connection connection) throws SQLException {
try {
Statement statement = connection.createStatement();
return statement.executeUpdate("INSERT INTO SCHEMA1.CRITICAL_ACTIONS(COLLEAGUE_ID,JOURNEY_ID,TYPE,PRODUCT,DESCRIPTION,META_DATA,STATUS) values('12345',11111111,'ABC','Lloyds','hellow','hello','START')");
} finally {
//connection.close();
}
}
public static final ResultSet FETCH_ACTION(Connection connection) throws SQLException {
try {
Statement statement = connection.createStatement();
return statement.executeQuery("SELECT * FROM SCHEMA1.CRITICAL_ACTIONS");
}finally {
connection.close();
}
}
}
Calling H2 Java Stored-procedure in Java :-
jdbcTemplate.update("CREATE ALIAS SAVE_ACTION FOR \"com.procedures.CRITICAL_ACTIONS.SAVE_ACTION\"");
jdbcTemplate.update("CREATE ALIAS FETCH_ACTION FOR \"com.procedures.CRITICAL_ACTIONS.FETCH_ACTION\"");
jdbcTemplate.getDataSource().getConnection().createStatement().execute("call SAVE_ACTION()");

Stored procedure in H2 database is same as java methods.So write java methods and can invoke using aliases.

The H2 is not supporting stored procedures. In place of stored procedure we can create a function which returns an output like a stored-procedures. Same as we're using in registerInOut parameters.
For example, if your QueryConst looks like this:
public static final String INSERT_EMPLOYEE = "{call INSERT_EMPLOYEE(?,?,?)}";
then,
We can use schema.sql(which executes before #Test)
DROP ALIAS IF EXISTS INSERT_EMPLOYEE;
CREATE ALIAS INSERT_EMPLOYEE FOR "com.test.EmployeeDaoImplTest.updateEmpStoredproc";
package com.test;
#ContextConfiguration(locations = { "classpath:configxmltest.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
#Sql(scripts = { "classpath:schema.sql" }, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public class EmployeeDaoImplTest {
public static final String INSERT_EMPLOYEE = "{call INSERT_EMPLOYEE(?,?,?)}";
#Autowired
EmployeeDaoImpl employeeDaoTest;
and other dependencies....(if any)
#Test
public void testUpdateEmployee() {
..ur logic if any input data settings
assertEquals("Inserted Successfully", employeeDaoTest.updateEmployee(input, INSERT_EMPLOYEE));
}
public static ResultSet updateEmpStoredproc(String name, String w, Integer i) throws SQLException {
SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("input", Types.VARCHAR, 255, 0);
rs.addColumn("error", Types.VARCHAR, 255, 0);
rs.addColumn("count", Types.INTEGER, 10, 0);
rs.addRow(0, "Inserted Successfully");
rs.addRow(1, 10);
return rs;
}
}

Related

Postgresql not connecting to android studio via java

I'm new to java and sql, I'm trying to connect to the postgresql program but I get an error and nothing happens. I can't figure out what's wrong
Unused import statement
Class 'ConnectPG' is never used
Method 'connectBD()' is never used
Method 'disconnection(java.sql.Connection)' is never used
I have two java class files, one "ConnectPG" I want to connect to postgresql through it, and the file "insertRecordExample" through it I try to enter values into the table. But nothing works. When I start debugging SEPARATELY on the "insertRecordExample" file, the program gives an error:
"
16:53:59: Executing ':app:InsertRecordExample.main()'...
enter code here`FAILURE: Build failed with an exception.
Blockquote
Where:
Initialization script 'C:\Users\fff\AppData\Local\Temp\InsertRecordExample_main__.gradle' line: 41
What went wrong:
A problem occurred configuring project ':app'.
Could not create task ':app:InsertRecordExample.main()'.
SourceSet with name 'main' not found.
Try:
Run with --stacktrace option to get the stack trace.
Run with --info or --debug option to get more log output.
Run with --scan to get full insights.
Get more help at https://help.gradle.org
BUILD FAILED in 110ms
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.
See https://docs.gradle.org/7.4/userguide/command_line_interface.html#sec:command_line_warnings
16:54:00: Execution finished ':app:InsertRecordExample.main()'.
"
Java File ConnectPG:
package com.example.a112new;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
public class ConnectPG {
Connection connect=null;
public Connection connectBD(){
try{
Class.forName("org.postgresql.Driver");
// localhost
connect=DriverManager.getConnection( "jdbc:postgresql://127.0.0.1:5432/112", "postgresql", "430890");
}catch (Exception er) {
System.err.println(er.getMessage());
}
return connect;
}
//
protected void disconnection(Connection con)throws Exception {
con.close();
}
}
Java File InsertRecordExample:
package com.example.a112new;
//package net.javaguides.postgresql.tutorial;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* Insert PrepareStatement JDBC Example
*
* #author Ramesh Fadatare
*
*/
public class InsertRecordExample {
//localhost
private final String url = "jdbc:postgresql://127.0.0.1:5432/112";
private final String user = "postgres";
// root
private final String password = "111111";
private static final String INSERT_USERS_SQL = "INSERT INTO users" +
" (user_id, lastname, firstname, patronymic, birth,phone,email,password) VALUES
" +
" (?, ?, ?, ?, ?, ?, ?, ?);";
public static void main(String[] argv) throws SQLException {
InsertRecordExample createTableExample = new InsertRecordExample();
createTableExample.insertRecord();
}
public void insertRecord() throws SQLException {
System.out.println(INSERT_USERS_SQL);
// Step 1: Establishing a Connection
try (Connection connection = DriverManager.getConnection(url, user, password);
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "FFFF");
preparedStatement.setString(3, "FFFF");
preparedStatement.setString(4, "FFFFF");
preparedStatement.setString(5, "2005-01-12");
preparedStatement.setString(6, "+79888888888");
preparedStatement.setString(7, "11111#gmail.com");
preparedStatement.setString(8, "1234567");
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
preparedStatement.executeUpdate();
} catch (SQLException e) {
// print SQL exception information
printSQLException(e);
}
// Step 4: try-with-resource statement will auto close the connection.
}
public static void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}}
Please help me understand what I am doing wrong.
I tried to identify the problem through logcat "--warning-mode=all" But it's no use, it doesn't give any errors at all. Gives errors only InsertRecordExample when I run it ONE! If I run the entire program, there are no errors as such, only those that I described above. I apologize in advance for my English.
If you are using android emulator to test your app then you shouldn't use 127.0.0.1 in your connection string, but 10.0.2.2, because if you are running both your server and your emulator on the same machine the 127.0.0.1 will refer to the emulator itself.
But generally JDBC doesn't work well at all when it comes to Android, so it may not be your mistake, but simply that JDBC doesn't work correctly. The best way of connecting to your database is using web services.

Why my Java project doesn't see my jTDS database driver

I'm trying to connect with SQL Server local database, I connected with it successfully from IntelliJ level, and there was information that I need to install jTDS driver to use it. I downloaded latest version of it and added as a library from my lib dir in project, despite this java says that it couldn't find the class, maybe I installed it wrong? Here is my code
import java.sql.*;
public class Main {
public static void main(String [] args) throws ClassNotFoundException, SQLException {
Class.forName("net.sourceforge.jtds");
Connection connection = DriverManager.getConnection("jdbc:jtds:sqlserver://./TPO");
Statement statement = connection.createStatement();
String sqlString = "SELECT * FROM Books";
ResultSet resultSet = statement.executeQuery(sqlString);
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}

I am trying to use a java record keeping project, but the program cannot seem to connect to the database

I have a simple library record keeping project i want to use, it is based on GUI & adds library book records, library members, books borrowed, etc.
It is implied the project uses DB, i.e. Mysql, however when i am trying to store a record into the DB the failed option executes, as in the record is not being able to be saved in the DB by the project.
The code is in modules so :
Code for establishing the connections
import java.sql.Connection;
import java.sql.DriverManager;
public class DB {
public static Connection getConnection(){
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","","");
}catch(Exception e){System.out.println(e);}
return con;
}
}
Code for getting the records:
import java.sql.*;
public class LibrarianDao {
public static int save(String name,String password,String email,String address,String city,String contact){
int status=0;
try{
Connection con=DB.getConnection();
PreparedStatement ps=con.prepareStatement("insert into
librarian(name,password,email,address,city,contact) values(?,?,?,?,?,?)");
ps.setString(1,name);
ps.setString(2,password);
ps.setString(3,email);
ps.setString(4,address);
ps.setString(5,city);
ps.setString(6,contact);
status=ps.executeUpdate();
con.close();
}catch(Exception e){System.out.println(e);}
return status;
}
public static int delete(int id){
int status=0;
try{
Connection con=DB.getConnection();
PreparedStatement ps=con.prepareStatement("delete from librarian where id=?");
ps.setInt(1,id);
status=ps.executeUpdate();
con.close();
}catch(Exception e){System.out.println(e);}
return status;
}
public static boolean validate(String name,String password){
boolean status=false;
try{
Connection con=DB.getConnection();
PreparedStatement ps=con.prepareStatement("select * from librarian where name=? and password=?");
ps.setString(1,name);
ps.setString(2,password);
ResultSet rs=ps.executeQuery();
status=rs.next();
con.close();
}catch(Exception e){System.out.println(e);}
return status;
}
}
Obvoiusly there are other code modules that interact with the DB as well, the project has a dedicated folder for all class files & similar for all ".java" files it is executed via a ".jar" file, but i do not know where to add the java-Mysql connector in the project folder, so it can access the DB.
MY queries are:
1) where in the project folder should i add the mysql connector to allow access to the mysql DB.
2) Any adding of the connector to the project has to be done manually (normally) or via netbeans.
3) if it has to be done via netbeans how do i recreate a new .jar file to execute the project.
It could be that you're closing the connection before closing the prepared statement. Make sure you close the prepared statement as well. Use a try-with-resources for both the connection and prepared statement if possible.
Another possible problem is you're not providing credentials when creating the connection. Does your MySQL DB not require user and pass auth?

Get SQLite user version via JDBC connection

I'm using JDBC to connect to a SQLite database:
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:/test.db");
Now my problem is that I'm not able to get the user version. I know that I can use PRAGMA but if I execute:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("PRAGMA user_version;");
then the retrieved result set will be closed (no data sets found).
Seems like you have problem in code not described in question because this snippet can set and get user_version without problem:
import java.sql.*;
public class Main {
public static void main(String[] args) throws Exception {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
try(Statement statement = conn.createStatement()) {
statement.execute("PRAGMA user_version = 10;");
}
try(Statement statement = conn.createStatement()) {
try(ResultSet rs = statement.executeQuery("PRAGMA user_version;")) {
System.out.println(rs.getInt(1));
}
}
}
}
Sqlite adapter:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.15.1</version>
</dependency>

Where can I find java.util.Properties file?

I am facing this error when I am trying to call database connection from MIDlet class. I have created a class file for JDBC connection and created an object for that class in MIDlet class. I trying to call that JDBC connection method in the startApp() method of MIDlet, but I am facing the following error.
cannot access java.util.Properties
class file for java.util.Properties not found
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/j2me","root","mysql");
1 error
in the code
import java.sql.*;
public class JDBCprogram {
public void runJDBC() {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/j2me","root","mysql");
Class.forName("com.mysql.jdbc.Driver");
Statement stmt = con.createStatement();
String sqlquery = "select * from employee";
ResultSet rs = stmt.executeQuery(sqlquery);
}
}
It sounds like something with your runtime class path is wrong, that could be a simple answer, unless the error is misleading.

Categories

Resources