Require help in calling a Java program from a batch file - java

I have a very simple Java program that connects to a PostgreSQL database to find if there are any databases by a specific naming pattern. When I find them I'm trying to delete them through the Java JDBC code. The Java code works fine when I manually run it, but what I'm trying to achieve is to automate this Java call through a batch file.
Can anyone throw any light on this? It's been frustratingly long that I'm struggling to find a solution for this.
My Java Code:
public class CreateBatchToCleanNamedDBs {
public static void main(String[] args) {
Connection connection = null;
BufferedReader input = null;
try {
String line;
RandomAccessFile batchFile = new RandomAccessFile("C:/batch.sql", "rw");
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "Welcome12!");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select datname from pg_database where datname like 'sample_db%';");
while (rs.next()) {
batchFile.writeBytes("DROP DATABASE " + rs.getString("datname") + ";\n");
System.out.println(rs.getString("datname"));
}
Process batchProcess = Runtime.getRuntime().exec("C:/Program Files/PostgreSQL/9.5/bin/psql -h localhost -U postgres -f C:/batch.sql");
input = new BufferedReader(new InputStreamReader(batchProcess.getInputStream()));
if(batchFile.length()!= 0) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
batchFile.close();
} catch(Exception exception) {
System.out.println("Exception caught: " + exception);
exception.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
}
}
My Batch file script:
#echo off
setlocal
if not defined JAVA_HOME goto :NoJavaFound
"%JAVA_HOME%\bin\java.exe" -jar "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs
goto :end
:NoJavaFound
echo JAVA_HOME environment variable is not set.
goto :end
:end
endlocal
I have both the jar file (my Java code, shown above) and the batch script file on the Desktop (same folder) and attempting to run - but I'm getting a NullPointerException, as my java code is missing the PostgreSQL jdbc driver. I've tried to add that as a parameter in multiple ways, but nothing works.
Error details:
C:\Users\pavan>C:\Users\pbonda\Desktop\deletedb.bat
Exception caught: java.lang.ClassNotFoundException: org.postgresql.Driver
java.lang.ClassNotFoundException: org.postgresql.Driver
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:20)
Exception in thread "main" java.lang.NullPointerException
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:45)

When calling java with an executable jar, the classpath provided to the java command is ignored.
You should either :
explicitly call the target class, with your jar in the classPath (i.e. "%JAVA_HOME%\bin\java.exe" -cp "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs)
specify the jar's classpath dependencies in its MANIFEST.MF file as well as its main class ; then you can execute the jar with java -jar. See this Oracle doc
add the postgresql jar into the your current jre's extentions library directory, or in the global extentions library directory. See this Oracle doc Deprecated in JavaSE 8, dropped in JavaSE9

try with:
"%JAVA_HOME%\bin\java.exe" -cp "%~dp0\postgresql-9.4.1207.jar;%~dp0\deletedb.jar" connect.postgresql.CreateBatchToCleanNamedDBs

Related

Why do I get java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver when mysql-connector-java-8.0.16.jar is in the classpath?

I get a java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver when I type this into the windows command line
javac src/*.java -d class -cp lib/*
java DBTest -cp lib/*
I have also tried using com.mysql.cj.jdbc without Driver at the end. I add newInstance() to line 11 so it was:
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
but there was no change.
I also tried it without Class.forName() since this is deprecated, but I got a java.sql.SQLException: No suitable driver found
mysql-connector-java-8.0.16.jar is the only file in lib. I have also tried putting it in in the folder where I run DBTest.java. I set the Classpath from the command line using
set CLASSPATH = .
and by creating the environment variable CLASSPATH through advanced system settings. I then tried compiling and running with and without -cp since it should be checking the current directory for the jar file.
I also tried to run this in eclipse, but eclipse crashed and will no longer open.
import java.sql.*;
public class DBTest{
public static void main(String args[]) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from employees Limit 10");
while(rs.next()) {
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getDouble(3));
}
con.close();
}catch(Exception e) {
System.out.println(e);
}
}
}
The entire error message is
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
You have the arguments to java in the wrong order. Putting arguments after the classname will pass those arguments to the main method of your class, it won't set the classpath.
You need to put the arguments before the classname. Also -d class is not a valid argument for java. In short, you need to use:
java -cp class:lib/* DBTest

How to establish connection between Java Program and Database without using IDE/ External Tools?

I want to write a Java Program for Establishing Connection between Java Program and Database, but I don't want to use any IDE like Netbeans, Eclipse, Visual Studio, XAMP, etc. I have jar files for Driver of required DBMS.
public class JDBCDemo
{
public static void main(String args[])
{
try
{
/**
* Steps for Establishing Connection between Java Application and Database
*/
//1. Load and Reginster Driver
Class.forName("com.mysql.jdbc.Driver");
//2. Establish a connection between Java Application and Database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/practicals", "root", "root123");
//3. Create Statement Object
Statement st = con.createStatement();
//4. Send and Execute SQL queries
ResultSet rs = st.executeQuery("SELECT * FROM tushar");
//5. Process the result from ResultSet object
while(rs.next())
{
System.out.println(rs.getString(1));
}
//6. Close the Connection
con.close();
}
catch(Exception e)
{
System.out.println(e.toString().trim());
}
}
}
It is showing error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
How to Establish connection ??
You need to add the mysql driver jar in the classpath before you run the program.
There are various ways to do so.
javac -cp "JAR_PATH" ClassName.java
java -cp "JAR_PATH" ClassName
Add the jar file in C:\Program Files\Java\\jre\lib\ext
set classpath=PATH_TO_JAR;
colon(:) is compulsory after jar file name
Compilling Program
javac -cp mysql-connector.jar: ProgramFileName.java
javac -cp mysql-connector.jar: JDBCDemo.java
Running Program
java -cp mysql-connector.jar: ProgramFileName
java -cp mysql-connector.jar: JDBCDemo
Note:- Simillar can be applied while using other jar files for performing other operations.
Sample Output

Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

I wanted to print the contents in a database but whenever I run this program I got this error saying that
Class not found java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
SQL exception occuredjava.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mydatabase
I have installed MySQL from this link http://dev.mysql.com/downloads/windows/installer/ its a 248mb file and installed completely. I can access my database within MySQL but can't able to access from netbeans. I separately downloaded the mysql-connector-java-5.1.4.jar and set the CLASSPATH but now also I got this error.
import java.sql.*;
public class jdbcResultSet {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/mydatabase","root",
"root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("SELECT * FROM employee");
System.out.println("id name job");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
}
catch(SQLException e){
System.out.println("SQL exception occured" + e);
}
}
}
First Check can you import import com.microsoft.sqlserver.jdbc.SQLServerDriver;
if it say com.microsft can not be resolved to a type that means u have to add your jar files to java build path and after that to deployment path from project properties.
java build path
Right click on project=>Properties=>Java Build Path=>
Librariess=>ADD External Jar file
deployment path
Right click on project=>Properties=>Deployment Assembly=>
ADDs=>Java Build Path Entries==> mssql_jdbc
The CLASSPATH environment variable is only used by the java.exe command and even then only when used without any of the -cp, -classpath, -jar arguments. It is ignored by IDEs.
So if you are running the application from your IDE place the mysql-connector.jar in your IDE's classpath
I downloaded the mysql-connector-java-5.1.4.jar file and placed in "C:\Program Files\MySQL\Java Connector" directory and edit System Environment Variable from control panel then set CLASSPATH as C:\Program Files\MySQL\Java Connector
Add the jar file, not the directory that the jar file is in.
Instead of,
C:\Program Files\MySQL\Java Connector
the CLASSPATH should include,
C:\Program Files\MySQL\Java Connector\mysql-connector-java-5.1.4.jar

Where do you put the Oracle's JDBC Thin Driver for Crystal Reports?

Where do you save the jdbc thin driver for Oracle? I have tried jre/lib/ext but my program, Crystal Reports keeps saying it can't find it. I figure I have saved it in the wrong place.
If I go to a command prompt and use:
C:\TEMP>java oracle.jdbc.OracleDriver
Oracle 11.2.0.3.0 JDBC 4.0 compiled with JDK6 on Fri_Aug_26_08:19:15_PDT_2011
Default Connection Properties Resource
Wed Oct 12 14:02:05 EDT 2011
So I know it is there.
edit: Since I could not get CR to work I tried a console app but it cannot find the driver:
package javaapplication1;
public class JavaApplication1 {
public static void main (String[] args) throws Exception
{
Class.forName ("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:#myserver:1521:mysid", "myid", "mypass");
// #//machineName:port/SID, userid, password
try {
Statement stmt = conn.createStatement();
try {
ResultSet rset = stmt.executeQuery("select BANNER from SYS.V_$VERSION");
try {
while (rset.next())
System.out.println (rset.getString(1)); // Print col 1
}
finally {
try { rset.close(); } catch (Exception ignore) {}
}
}
finally {
try { stmt.close(); } catch (Exception ignore) {}
}
}
finally {
try { conn.close(); } catch (Exception ignore) {}
}
}
}
edit: On my computer it is here:
C:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\jdk\jre\lib\ext
Just put it in the application's runtime classpath. The file system paths covererd by the classpath depends on how you're executing the application.
Based on your question history I see that you're using JSP/Servlets, which thus means that it's a web application in flavor of a WAR file which runs in an appserver. In that case, the JAR file needs to go in webapp's own /WEB-INF/lib folder or in the appserver's own /lib folder.
If it were a plain vanilla Java application .class file with a main() method which is to be executed by java command, then you'd have to use the -cp (-classpath) argument to specify the runtime classpath. It takes a collection of (semi)colon separated disk file system paths.
If it were a JAR file, then it had to be specified in the Class-Path entry in JAR's /META-INF/MANIFEST.MF file. This can be relative to the java -jar command's working directory.
You should really avoid putting 3rd party libraries in JRE's /lib folder. This would potentially introduce classpath problems with all other existing applications which use the same JRE.

Java connectivity with PostgreSQL

Can someone please tell me how to connect java file to postgresql database (if possible with code n explanation)
Google is a good start
http://jdbc.postgresql.org/
Here is an example test.java
import java.sql.*;
class test
{
public static void main(String[] args) {
String hostname="", dbname="", username="", password="";
try {
int argno = 0;
hostname = args[argno++];
dbname = args[argno++];
username = args[argno++];
password = args[argno++];
} catch (Exception ex) {
System.err.println("Usage: java -cp driver.jar:. test [hostname] [dbname] [username] [password]");
System.exit(1);
}
try {
Class.forName("org.postgresql.Driver");
Connection connection =
DriverManager.getConnection(
"jdbc:postgresql://"+hostname+"/"+dbname,
username,
password
);
ResultSet rs = connection.createStatement().executeQuery(
"select version() as version"
);
while ( rs.next() ) {
System.out.println(rs.getString("version"));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Download a current driver from JDBC download page, compile this and run like this on Unices:
java -cp [driver_file_name].jar:. test [hostname] [dbname] [username] [password]
On Windows:
java -cp [driver_file_name].jar;. test [hostname] [dbname] [username] [password]
Just wanted to expound on Tometzky's answer for other beginners using the Netbeans IDE in UNIX like me.
I want the driver to be recognized as a library in the IDE. If you go to Tools->Libraries, you will see the current list. Hit "New Library" and type "PostgreSQL JDBC Driver" or whatever name you want to give it. Then in the Classpath tab, hit "Add JAR/Folder" and point to where you've saved your downloaded driver. I'm not sure if there is a "correct" place to store it, I think it rather depends on how you back up your system and if multiple users share it. Somewhere in your home directory is fine.
After that, make a new project of type "Java Application" and paste Tometzky's code into main. In your project tree, right click on Libraries and add the JDBC driver directly to the project. Now you don't have to worry about specifying the driver on the command line.
Build your project and head over to its "dist" folder. Now you can run it with the command
java -jar myprojectname.jar 127.0.0.1 [dbname] [user] [pw]
That of course assumes you are connect to the database server on your own machine. [user] and [pw] refer to your PostgreSQL username and pw.
Also, when you download the documentation it comes as a bunch of html files. Save them somewhere and point your browser to the index.html file (in Firefox it is File-->Open File).

Categories