Firebird connection using Spring Boot - java

How to create a Firebird connection using Spring Boot to make views in SQL using the Firebird database? I have no idea how to build this.
try {
Class.forName("org.firebirdsql.jdbc.FBDriver");
Connection con= DriverManager.getConnection("jdbc:firebirdsql:localhost/3050:C:/DB/DASHBOARD.FDB","sysdba","masterkey");
Statement stm= con.createStatement();
ResultSet res= stm.executeQuery("SELECT * FROM TBLEMPLOYEE");
while (res.next()) {
System.out.println("DASHBOARD LASTNAME:"
+ res.getString("LASTNAME"));
}
} catch (Exception e) {
System.out.println(e);
}
I tried to make a connection string, but without success because Spring doesn't recognize it.

Take the following steps:
Go to https://start.spring.io/
Configure it with Maven (or Gradle if you prefer that)
Enter the desired coordinates for your project
Add dependency JDBC
Click Generate and unpack the zip to a location on your computer
Open the project in you favorite IDE
In the pom.xml, in the dependencies section add Jaybird (the Firebird JDBC driver):
<dependency>
<groupId>org.firebirdsql.jdbc</groupId>
<artifactId>jaybird</artifactId>
</dependency>
Or, if you used Gradle, add to the dependencies section of build.gradle:
runtimeOnly 'org.firebirdsql.jdbc:jaybird'
In src/main/resources/application.properties add:
spring.datasource.url=jdbc:firebirdsql://localhost/employee
spring.datasource.username=sysdba
spring.datasource.password=masterkey
In the package generated by the initializr (default com.example.demo), add a new class SimpleRunner:
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
#Component
public class SimpleRunner implements CommandLineRunner {
private final DataSource dataSource;
public SimpleRunner(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public void run(String... args) throws Exception {
try (var connection = dataSource.getConnection();
var stmt = connection.createStatement();
var rs = stmt.executeQuery("select first_name, last_name from employee")) {
while (rs.next()) {
System.out.printf("%s %s%n",
rs.getString("first_name"), rs.getString("last_name"));
}
}
}
}
This very basic application will connect to the Firebird example database employee, and print out the first and last names of the employees in the employee table.

Related

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?

Implementing DataSource in Java to connect to my database

I'm trying to write a class that implements DataSource. This seems simple enough, but the examples I'm seeing for Oracle all declare the class like this:
public class ConnectionPoolingBean implements SessionBean {
....
}
I would expect to see something more like this:
public class MyDataSource implements DataSource {
....
}
Also, I don't understand how the connection is actually working. The getConnection() method only takes the arguments for username and password. So how am I connecting to my database?
Ultimately, what I need to understand is how do I connect to my database and return a result set from a query using DataSource. I just don't see any clear examples of how write a class to use this on my WebApp.
Here's what I've been reading from, which is now just confusing me.
https://docs.oracle.com/javase/tutorial/jdbc/basics/sqldatasources.html
http://docs.oracle.com/javase/7/docs/api/javax/sql/DataSource.html
Use any connection pool for your use case.If you are using app server you can use app server connection pool or use opensource dbcp connection pool mechanism.
<!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
Example
import org.apache.commons.dbcp2.BasicDataSource;
public class DataBaseUtility
{
private static BasicDataSource dataSource;
private static BasicDataSource getDataSource()
{
if (dataSource == null)
{
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:mysql://localhost/test");
ds.setUsername("root");
ds.setPassword("password");
ds.setMinIdle(5);
ds.setMaxIdle(10);
ds.setMaxOpenPreparedStatements(100);
dataSource = ds;
}
return dataSource;
}
public static void main(String[] args) throws SQLException
{
try (BasicDataSource dataSource = DataBaseUtility.getDataSource();
Connection connection = dataSource.getConnection();
PreparedStatement pstmt = connection.prepareStatement("SELECT * FROM account");)
{
System.out.println("The Connection Object is of Class: "+connection.getClass());
try (ResultSet resultSet = pstmt.executeQuery();)
{
while (resultSet.next())
{
System.out.println(resultSet.getString(1) + "," + resultSet.getString(2) + "," + resultSet.getString(3));
}
}
catch (Exception e)
{
connection.rollback();
e.printStackTrace();
}
}
}
}

JDBC JAVA No suitable driver found for jdbc:mysql://localhost:3306/voting

Hello im trying to connect to a mysql database using JDBC my code is below.I get an error as such No suitable driver found.Searching around I found that the usual error is syntax or missing the jar file from the class path.I tried both of these solutions and dont know what to do next it wont connect.Also to manage the databases I have WAMP and mySQL workbench installed not sure if its related.
package test.jdbc;
import java.sql.*;
public class jdbctester {
public static void main(String[] args)
{
try
{
Connection myconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/voting","root","Vanquish123");
Statement myStmt=myconn.createStatement();
ResultSet myRs=myStmt.executeQuery("select * from electoral");
/*
while(myRs.next())
{
System.out.println(myRs.getString("state")+","+myRs.getString("perDem"));
}
*/
}
catch(Exception exc)
{
exc.printStackTrace();
}
}
}
Try this:
Class.forName("fully qualified driver class name");
Java Class.forName, JDBC connection loading driver
this post states that you should not need it but it will not hurt you to try.
you have to add "com.mysql.jdbc_5.1.5.jar" in to your project build path... go to project property>build Path> library> add external jar and add jar file.
Connection conn = null;
try {
// Register JDBC driver
Class.forName(DRIVER).newInstance();
// Open a connection
conn = DriverManager.getConnection(Local_URL + , USERNAME, PASSWORD);
System.out.println("Connected Database Successfully...\n\n");
} catch (Exception se) {
throw new AppException("Failed to create Local Database connection", se);
}
return conn;

Stored Procedure in H2 Database

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;
}
}

Categories

Resources