H2 data added wont refresh until disconnect - java

This is my code:
package logic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:./Database/Data", "Gustavo", "123456");
stmt = conn.createStatement();
stmt.execute("CREATE TABLE TEST(ID INT PRIMARY KEY,NAME VARCHAR(255));");
stmt.execute("INSERT INTO TEST VALUES(1, 'John');");
ResultSet rs = stmt.executeQuery("select * from test");
while (rs.next()) {
System.out.println("id " + rs.getInt("id") + " name " + rs.getString("name"));
}
conn.close();
}
}
I can add the data and display it and if I run the code again (commenting the CREATE TABLE and INSERT INTO) it displays the data.
The problem is that when I go to the H2 console, it doesn't show anything unless I disconnect and reconnect. After I do that, it shows any changes made or data added to the database.
Is there a problem or that's how the H2 console works?
(I'm on Ubuntu 20.04, using vs code and gradle)
Edit: I solved it
The problem was in the code I was using it in embebed mode and it only allows one connection at a time. Once I changed it to server mode using:
String url = System.getProperty("user.dir") + "/Database/Data";
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/" + url, "Gustavo", "123456");

I solved it
The problem was in the code I was using it in embebed mode and it only allows one connection at a time. I changed it to server mode using:
String url = System.getProperty("user.dir") + "/Database/Data";
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/" + url, "Gustavo", "123456");

Related

How come I'm getting authenticate error, but when I login via the app, I am able to log in

com.microsoft.sqlserver.jdbc.SQLServerException: Failed to
authenticate the user fakeaccount#gmail.com in Active Directory
(Authentication=ActiveDirectoryPassword). at
com.microsoft.sqlserver.jdbc.SQLServerADAL4JUtils.getSqlFedAuthToken(SQLServerADAL4JUtils.java:62)
~[mssql-jdbc-8.4.1.jre8.jar:na] at
com.microsoft.sqlserver.jdbc.SQLServerConnection.getFedAuthToken(SQLServerConnection.java:4442)
~[mssql-jdbc-8.4.1.jre8.jar:na] at
com.microsoft.sqlserver.jdbc.SQLServerConnection.onFedAuthInfo(SQLServerConnection.java:4415)
~[mssql-jdbc-8.4.1.jre8.jar:na]
As Suggested by Jatin. You could refer to Azure Active Directory authentication document, where you could find different authentication methods and below is the sample example of connecting Azure Active Directory with MSI authentication method.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
public class AAD_MSI {
public static void main(String[] args) throws Exception {
SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("aad-managed-demo.database.windows.net"); // Replace with your server name
ds.setDatabaseName("demo"); // Replace with your database name
ds.setAuthentication("ActiveDirectoryMSI");
// Optional
ds.setMSIClientId("94de34e9-8e8c-470a-96df-08110924b814"); // Replace with Client ID of User-Assigned Managed Identity to be used
try (Connection connection = ds.getConnection();
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT SUSER_SNAME()")) {
if (rs.next()) {
System.out.println("You have successfully logged on as: " + rs.getString(1));
}
}
}
}

ucanaccess SQL Exception: invalid cursor state: identified cursor is not open

I am a little bit confused,
I am trying to insert multiple rows to MS Access database from a java program using ucanaccess Java library.
I don't understand why the above (check title) SQL Exception is thrown when calling the 2nd insertRow() method?
The Exception is NOT thrown either by calling con.setAutoCommit(false); & con.commit(); methods or by re-executing the SQL query using the command rs = st.executeQuery(sql);. I also do not understand why the problem is solved by doing one of the above. What changes?
Thanks in advance.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class db1 {
private Connection con;
protected Statement st;
protected ResultSet rs;
public db1() {
connect();
}
public void connect() {
try {
String driver = "net.ucanaccess.jdbc.UcanaccessDriver";
Class.forName(driver);
String db = "jdbc:odbc:Database1";
con = DriverManager.getConnection
("jdbc:ucanaccess://C:\\Users\\Κώστας\\Desktop\\Database1.accdb");
st = con.createStatement
(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE,
ResultSet.HOLD_CURSORS_OVER_COMMIT)
// con.setAutoCommit(false);
String sql = "select * from TableA";
rs = st.executeQuery(sql);
rs.insertRow();
// rs = st.executeQuery(sql);
rs.insertRow(); // HERE the SQL Exception is thrown.
// con.commit();
}
catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
new db1();
}
}
UCanAccess has some known issues with updatable ResultSets because it uses triggers on the HSQLDB backing tables to push the changes to the Access database file. A side effect of those triggers is that they can leave the HSQLDB ResultSet in an invalid state.
The problem you are experiencing may not manifest itself with con.setAutoCommit(false); because the triggers probably don't flush the changes to the Access database until the JDBC transaction is committed.

Can I get direct all signature of stored procedure from oracle using jdbc api insted of "select* from "?

I am using JDBC to get matadta of stored procedures from different databases. I am trying to get procedure signatures with parameteres. I have tried to get stored procedure names by using getProcedures() function and parameter name with getProcedureColumns().
The problem is when I am trying to get parameters from procedures/functions in Oracle Database 11g using getProcedureColumns() it will return information for only those procedures which have parameters. How can I get information for all procedures by using JDBC only? I don't want to use sql commands for this. Below is the code I am using for finding parameter information.
package jdbc.core;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.DatabaseMetaData;
import com.mysql.jdbc.Statement;
public class Main {
public static void main(String[] args) throws Exception {
Connection conn = null;
System.out.println("Got Connection.");
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:#192.192.6.144:1521","system","");
java.sql.Statement st = conn.createStatement();
java.sql.DatabaseMetaData dbMetaData = conn.getMetaData();
ResultSet rs = dbMetaData.getProcedureColumns(null, "dbo", "%", "%");
while (rs.next()) {
String procedureName = rs.getString(3);
String columnName = rs.getString(4);
System.out.println("procedureSchema=" + procedureSchema);
System.out.println("procedureName=" + procedureName);
System.out.println("columnName=" + columnName);
}
}

Issue in running code using JasperReports API on different machines

I created a Java project which will use JasperReports API. I have tested this inside and outside NetBeans (same machine) and it works fine. But when I try to run it on another machine the report wont load.
My code is:
package reportmonitory;
import java.sql.*;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.swing.JRViewer;
import javax.swing.*;
public class monthlyreport extends JFrame {
Connection con;
Statement stmt;
ResultSet rs;
void showReport() {
try {
String host = "jdbc:mysql://192.168.10.11/rmcdb";
String uName = "root";
String uPass = "";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String reportName = "reports/finalreport.jasper";
java.io.InputStream is = this.getClass().getClassLoader().getResourceAsStream(reportName);
JasperPrint print = JasperFillManager.fillReport(is, null, con);
JRViewer viewer = new JRViewer(print);
viewer.setOpaque(true);
viewer.setVisible(true);
this.add(viewer);
this.setSize(1000, 1000);
this.setVisible(true);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
} catch (Exception ex) {
System.out.println("CAUSE: " + ex.getCause());
System.out.println("MESSAGE" + ex.getMessage());
System.out.println("LOCAL MESSAGE" + ex.getLocalizedMessage());
ex.printStackTrace();
}
}
public static void main(String args[]) {
new monthlyreport().showReport();
}
}
Here are some suggestions / things to look into:
Port forwarding for databases behind firewalls
Specify port in case the database's connection port has been changed
Make sure 'reports/finalreport.jasper' exists
Packaging (due to project moving around)
Ensure all .jar's / JasperReport API files are there
All other files this project calls are there
Network problem / not finding hostname: 192.168.10.11
EDIT:
The error comes from being unable to find 'npa logo.jpg'. Make sure it exists on the correct path. I notice you are looking for it on 'C:\Users\mwaluda' and you are running JaspterReports on C:\Users\Aboud. If this is a different machine, would that path still be valid?

How do I connect to a SQL Server 2008 database using JDBC?

I have MSSQL 2008 installed on my local PC, and my Java application needs to connect to a MSSQL database. I am a new to MSSQL and I would like get some help on creating user login for my Java application and getting connection via JDBC. So far I tried to create a user login for my app and used following connection string, but I doesn't work at all. Any help and hint will be appreciated.
jdbc:jtds:sqlserver://127.0.0.1:1433/dotcms
username="shuxer" password="itarator"
There are mainly two ways to use JDBC - using Windows authentication and SQL authentication. SQL authentication is probably the easiest. What you can do is something like:
String userName = "username";
String password = "password";
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
after adding sqljdbc4.jar to the build path.
For Window authentication you can do something like:
String url = "jdbc:sqlserver://MYPC\\SQLEXPRESS;databaseName=MYDB;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
and then add the path to sqljdbc_auth.dll as a VM argument (still need sqljdbc4.jar in the build path).
Please take a look here for a short step-by-step guide showing how to connect to SQL Server from Java using jTDS and JDBC should you need more details. Hope it helps!
You can use this :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class ConnectMSSQLServer
{
public void dbConnect(String db_connect_string,
String db_userid,
String db_password)
{
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from sysobjects where type='u'";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)
{
ConnectMSSQLServer connServer = new ConnectMSSQLServer();
connServer.dbConnect("jdbc:sqlserver://<hostname>", "<user>",
"<password>");
}
}
I am also using mssql server 2008 and jtds.In my case I am using the following connect string and it works.
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( "jdbc:jtds:sqlserver://<your server ip
address>:1433/zacmpf", userName, password );
Statement stmt = con.createStatement();
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
Try to use like this: jdbc:jtds:sqlserver://127.0.0.1/dotcms; instance=instanceName
I don't know which version of mssql you are using, if it is express edition, default instance is sqlexpress
Do not forget check if SQL Server Browser service is running.
You can try configure SQL server:
Step 1: Open SQL server 20xx Configuration Manager
Step 2: Click Protocols for SQL.. in SQL server configuration. Then, right click TCP/IP, choose Properties
Step 3: Click tab IP Address, Edit All TCP. Port is 1433
NOTE: ALL TCP port is 1433
Finally, restart the server.
Simple Java Program which connects to the SQL Server.
NOTE: You need to add sqljdbc.jar into the build path
// localhost : local computer acts as a server
// 1433 : SQL default port number
// username : sa
// password: use password, which is used at the time of installing SQL server management studio, In my case, it is 'root'
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conn {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Connection conn=null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=company", "sa", "root");
if(conn!=null)
System.out.println("Database Successfully connected");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Try this.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class SQLUtil {
public void dbConnect(String db_connect_string,String db_userid,
String db_password) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(db_connect_string,
db_userid, db_password);
System.out.println("connected");
Statement statement = conn.createStatement();
String queryString = "select * from cpl";
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
} }
public static void main(String[] args) {
SQLUtil connServer = new SQLUtil();
connServer.dbConnect("jdbc:sqlserver://192.168.10.97:1433;databaseName=myDB",
"sa",
"0123");
}
}
Try this
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
String url ="Jdbc:jtds:sqlsever://ip/instanceName;instance=instanceName;databseName=dbName;user=yourUser;password=yourpass;";

Categories

Resources