Following is my Java code. In linux, it is working fine but in Windows I'm unable to insert data into the database on local disk. In NetBeans get it all right but .jar file not. JDBC driver see be good.
Connecting to database:
public static Connection connectToDb() {
try {
Connection connection = null;
DriverManager.registerDriver(new org.sqlite.JDBC());
//LINUX PATH
if (OSDetector.isLinux()) {
connection = DriverManager.getConnection("jdbc:sqlite:/home/" + userNameLinux + "/PDFMalwareDataAnalyser/DatabaseSQLite/database.db", NAME, PASSWORD);
//WINDOWS PATH
} else {
connection = DriverManager.getConnection("jdbc:sqlite:C:\\PDFMalwareDataAnalyser\\DatabaseSQLite\\database.db", NAME, PASSWORD);
}
connection.setAutoCommit(true);
if (connection != null) {
System.out.println("Otvorená.");
}
return connection;
} catch (SQLException e) {
System.err.println(e.getClass().getName() + e.getMessage());
// System.exit(0);
}
return null;
}
Insertion:
public void insertDataToDatabase(int idReport) throws SQLException {
connection = new SQLiteJDBC().connectToDb();
PreparedStatement insertCommunication = connection.prepareStatement("insert into table_communication values(?,?);");
insertCommunication.setString(2, communicationsFinal.toString());
try {
insertCommunication.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
insertCommunication.close();
connection.close();
System.out.println("1. --- Insert do tabuľky TABLE_COMMUNICATION OK ---");
}
Try this:
connection = DriverManager.getConnection("jdbc:sqlite:C:/PDFMalwareDataAnalyser/DatabaseSQLite/database.db")
Related
Hello my connection code works in other class but in here says:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Cannot find the driver in the classpath!
my code is following:
tfield2.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(tfield2.getText().equals("REC1U")) {
String url = "jdbc:mysql://localhost:3306/redpraire";
String username = "username";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
Statement stmt = connection.createStatement();
try {
ResultSet rs = stmt.executeQuery("SELECT * FROM product");
while(rs.next()) {
// some code here
}
rs.next();
} finally {
stmt.close();
}
} catch (SQLException ex) {
throw new IllegalStateException("Cannot connect the database!", ex);
}
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException ex) {
throw new IllegalStateException("Cannot find the driver in the classpath!", ex);
}
} else {
}
} else if(e.getKeyCode() == 121) {
frame.setVisible(false);
frame.dispose();
new QueryMenu();
}
}
});
i have tried different ways to change it but nothing will work... in separate class this connection works perfectly fine...
i am just out of ideas. any help?
Try running it as follows:
java -cp path-to-jdbc-driver-jar your-java-class
e.g.
java -cp hsqldb-2.2.9.jar org.hsqldb.util.DatabaseManagerSwing
I hope, you are already aware of -classpath or -cp option. If not, go through this documentation.
do you install MySQL jdbc driver
Verify you your data data base connection to
Database -> new connection -> test connection
I'm playing with this kind of database, and I've tried to close the HSQLDB connection after I used it, but it's still opened at the end.
Code:
//----This methods are in a specific connection class file
public static Connection conn = null;
public static Connection getConnection(){
try {
input = new FileInputStream("PathToMyPropertiesFile");
prop.load(input);
//The properties constants are correctly checked
Class.forName(prop.getProperty("DRIVER_HSQLDB"));
conn = DriverManager.getConnection(prop.getProperty("CONN_HSQLDB"));
}
catch(ClassNotFoundException | SQLException e) {
LOG.log(null,"Error: "+e);
}
catch (IOException ex) {
LOG.log(null,"FILE ERROR: "+ex);
}
finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
LOG.log(null,"CLOSE ERROR: "+e);
}
}
}
return conn;
}
public static boolean stopConn() {
try {
if(conn != null) {
conn.close();
System.err.println("\nCLOSE CONN\n"+conn);
return true;
}
}
catch (SQLException e) {
e.printStackTrace();
return false;
}
return false;
}
//========= the other class file with the methods to use the conneciton
public static boolean insertUser(String uName, String uEmail){
Connection con;
con = ConnectionDB.getConnection();
PreparedStatement ps = null;
try {
String consulta = "insert into USERS (\"NICK\",\"EMAIL\") VALUES(?,?);";
ps = con.prepareStatement(consulta);
System.err.println(ps);
ps.setString(1,uName);
ps.setString(2,uEmail);
System.err.println("\nASSIGNATION\n"+ps);
if(ps.executeUpdate() == 1) {
System.err.println("\nTRUE\n");
return true;
}
}
catch(SQLException e) {
e.printStackTrace();
}
finally {
try {
System.err.println("\nFINALLY\n"+ps);
if(ps != null) {
ps.close();
System.err.println("\nCLOSE PS\n"+ps);
}
if(con != null) {
con.close();
System.err.println("\nCLOSE CON\n"+con);
if(ConnectionDB.stopConn()) {
System.err.println("\nALL IS OK\n"+ConnectionDB.conn);
}
else {
System.err.println("\nMEEEEKKKK!!!\n"+ConnectionDB.conn);
}
}
}
}
return false;
}
The console give me this results, and I don't know why never the connection is closed because I tried to close it twice. If someone has an idea please tell me.
org.hsqldb.jdbc.JDBCPreparedStatement#4501280b[sql=[insert into USERS ("NICK","EMAIL") VALUES(?,?);], parameters=[[null], [null]]]
ASSIGNATION
org.hsqThis is my cldb.jdbc.JDBCPreparedStatement#4501280b[sql=[insert into USERS ("NICK","EMAIL") VALUES(?,?);], parameters=[[extra], [extra#mail.com]]]
TRUE
FINALLY
org.hsqldb.jdbc.JDBCPreparedStatement#4501280b[sql=[insert into USERS ("NICK","EMAIL") VALUES(?,?);], parameters=[[extra], [extra#mail.com]]]
CLOSE PS
org.hsqldb.jdbc.JDBCPreparedStatement#4501280b[closed]
CLOSE CON
org.hsqldb.jdbc.JDBCConnection#3e5b87f5
CLOSE CONN
org.hsqldb.jdbc.JDBCConnection#3e5b87f5
ALL IS OK
org.hsqldb.jdbc.JDBCConnection#3e5b87f5
Closing a JDBC connections does not close an in-process database. This allows you to open and close different connections during the runtime of your application.
You need to execute a JDBC Statement to shutdown the database. The SQL statement to execute is "SHUTDOWN".
It is possible to add a connection property "shutdown=true" to the JDBC connection URL to force a quick shutdown when the last connection to the in-process database is closed. But this is mainly useful for readonly or test databases. A full SHUTDOWN allows the database to open quickly the next time a connection is made.
See the Guide http://hsqldb.org/doc/2.0/guide/running-chapt.html#rgc_inprocess
I try to connect to db2 from java, here is my code:
public class Db2Connection {
public static void main(String[] args) {
String jdbcClassName="com.ibm.db2.jcc.DB2Driver";
String url="jdbc:db2://localhost:50001/TEST";
String user="user1";
String password="pass";
System.out.println("before try-catch");
Connection connection = null;
try {
System.out.println("try");
//Load class into memory
Class.forName(jdbcClassName);
//Establish connection
System.out.println("before conn");
connection = DriverManager.getConnection(url, user, password);
System.out.println("after conn");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(connection!=null){
System.out.println("Connected successfully.");
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
To be clear, I add db2jcc.jar to my project and run code with valid url. Program cannot jump over line:
connection = DriverManager.getConnection(url, user, password);
I receive no errors or exception, application just not execute. I have no idea how deal with it, can anyone help me?
Try, after removing colon like :
String url="jdbc:db2//localhost:50001/TEST";
I'm totally noob! I have automative test framework previously written for single Mysql server with 2 database on it. And DB connection was looked like
public static Connection getConnection() {
if (conn == null) {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://"
+ PropertyHandler.getInstance().getValue(PropertyKeys.dbHost)
+ ":"
+ PropertyHandler.getInstance().getValue(PropertyKeys.dbPort),
PropertyHandler.getInstance().getValue(PropertyKeys.dbUser),
PropertyHandler.getInstance().getValue(PropertyKeys.dbPass));
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return conn;
}
public static void closeConnection() {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
But now they are on different IPs . Please provide simple example how to fix it. Thanks.
Java DB connection is just a Object. you can create 2 connection Objects for 2 Mysql Servers.
you have getConnection() method created. so you just need to change the method to accept connection parameters.
for example:
Connection db1 = getConnection(server_ip, db, username, password);
Connection db2 = getConnection(server_ip2, db, username2, password2);
public static Connection getConnection(String ip, String db, String user, String pass) {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://"+ip+"/"+db+"?" +
"user="+user+"&password="+pass);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return conn;
}
I wrote a java program which retrieve data from a PG gb, process them, and write them in an Oracle DB.
While the PG part is fully working, the Oracle one has issues.
I can connect to the DB, but every query ends with a rollback (ResultSet with Oracle is always null)
Of course i have both PG and Oracle JDBC driver.
Here are my DBs object and testing queries
private final static PostgresDB postgres = new PostgresDB("jdbc:postgresql://192.168.2.23:5432/T18CLEAN", "myPGUser", "myPGPasswd", true);
private final static OracleDB oracle = new OracleDB("jdbc:oracle:thin:#192.168.2.20:1521/EFFEVI.T18FV.IT", "myOracleUser", "myOraclePasswd");
private final static String testPostgres = "SELECT product_pricelist_item.x_product_name FROM public.product_pricelist_item;";
private final static String testOracle = "SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Then I setup the 2 connections:
PG:
public Connection getConnect() throws ClassNotFoundException {
System.out.println("-------- Posgres JDBC Connection Testing ------");
String url = c_url;
Connection conn = null;
Properties props = new Properties();
props.setProperty("user", user);
props.setProperty("password", passwd);
props.setProperty("ssl", boolToString(sslEnabled));
try{
Class.forName("org.postgresql.Driver");
System.out.println("Postgres JDBC Driver Registered!");
} catch(ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return null;
}
try {
conn = DriverManager.getConnection(url, props);
System.out.println("You made it, take control your Postgres database now!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Failed to make connection to Postgres DB!");
}
return conn;
}
Oracle:
public Connection getConnect(){
Connection connection = null;
System.out.println("-------- Oracle JDBC Connection Testing ------");
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your Oracle JDBC Driver?");
e.printStackTrace();
return connection;
}
System.out.println("Oracle JDBC Driver Registered!");
try {
connection = DriverManager.getConnection(c_url, user, passwd);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return connection;
}
if (connection != null) {
System.out.println("You made it, take control your Oracle database now!");
return connection;
} else {
System.out.println("Failed to make connection to Oracle DB!");
}
return connection;
}
After all these pass i perform queries
public ResultSet executeCommand(Connection c, String command) {
Statement st = null;
ResultSet rs = null;
try {
st = c.createStatement();
rs = st.executeQuery(command);
} catch (SQLException e) {
}
if(rs==null){
System.out.println("Failed to Execute command " + command);
} else {
System.out.println("Command Executed: " + command);
}
return rs;
}
Assuming that there are no parameters error... What could it be? Any help?
Thank you very much
Remove a semicolon at the end of the query.
Use this:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI";
instead of this one:
private final static String testOracle =
"SELECT EFFEVI.PRESA_ORDINI.PO_CLIENTE FROM EFFEVI.PRESA_ORDINI;";
Also don't silently "swallow" an exception in your code:
} catch (SQLException e) {
}
Rethrow the exception, or at least print the error to the log:
} catch (SQLException e) {
log.error("Error while executing query " + command, e);
throw new RuntimeException("Error while executing query " + command, e);
}