Java connectivity with PostgreSQL - java

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).

Related

JPackage (incubator) and SQLite database problem

I could use some help again, out of ideas. :(
I am making JavaFX application that will use SQLite database. OpenJDK 14 with OpenJFX14 is used. In my Eclipse all is working perfectly. I tried for test to make installer with JPackage and that worked too. When I start installed application it starts ok, but for some reason refuse to connect with database.
Here is my project structure:
I have a button where when Stage is loaded I check connection. It is in file PocetnaController:
//testiranje konekcije nakon instalacije
#FXML
public void btnObracunClick(ActionEvent event) {
lblStatus.setText(model.povezanaBaza());
}
And this is code from PocetnaModel that is called:
public String povezanaBaza() {
this.konekcija = Konekcija.poveziBazu();
return (this.konekcija != null) ? "Веза са базом успостављена" : "Повезивање са базом није успело.";
}
When true it returns "Database connection established" in my language and when false "Connection with database failed".
I repeat, in Eclipse all works well. But, when start installed app I am getting "Connection with database failed". So connection returning null for some reason.
My db file is coppied by JPackage in /app folder. I tried to copy manualy Porez.db to root folder where *.exe is. Strange thing, status label doesn't change in that case. And it should, it must return true or false, don't understand that.
This is stage look when started:
Even if I rename database file in /app folder, so it can't be found my connection still returning false and update status accordingly which is ok.
Here is entire Konekcija file who has a role to take care of connection:
public static Connection poveziBazu() {
File baza = new File("Porez.db");
try {
if (baza.exists()) {
Connection con = DriverManager.getConnection("jdbc:sqlite:Porez.db");
return con;
} else {
return null;
}
} catch (Exception e) {
return null;
}
}
My first suspect is something is wrong with my created JAR, but can't be sure. Makes no sense to me to work in Eclipse and no after install.
There are several places you need to check and possibly fix if you ran jpackage with:
jpackage --name SQLiteTest --input C:\Users\Dalibor\Documents\NetBeansProjects\SQLiteTest\dist --main-jar SQLiteTest.jar --runtime-image hello\myjre
Turn on Windows console so that you can see the error messages it is providing - use jpackage --win-console.
After installing your jpackaged release, check the release directory structure.
Make sure it contains the sqllite-jdbc.jar file.
If NOT found fix your --input directories to add the jar.
Check the app\xxx.cfg file for your generated application.
It must contain all your jar dependencies including sqlite-jdbc.jar such as:
app.classpath=$ROOTDIR\app\jars\xxxx.jar;$ROOTDIR\app\jars\sqlite-jdbc.jar
Check that the jlink command you used to build the runtime image hello\myjre includes --add-modules java.sql to combine with the required SQL dependencies.
The app structure created by the installer that jpackage builds is different to the structure you have in Eclipse - files are under app directory, and most importantly the release is only editable with Administrator privileges. Use System property java.launcher.path to adjust the location of the SqlLite database to an editable location
and don't mask exceptions:
public static Connection poveziBazu() {
File baza = new File("Porez.db");
String jhome = System.getProperty("java.launcher.path");
if (jhome != null) {
baza = new File(System.getProperty("user.home"), "Porez.db");
}
System.out.println("Connecting to "+baza.getAbsolutePath()+" exists()="+baza.exists());
try {
return DriverManager.getConnection("jdbc:sqlite:"+baza.getAbsolutePath());
} catch (Exception e) {
System.out.println("Failed connecting to: "+baza);
throw new RuntimeException("Failed to open or create db: "+baza, e);
}
}

Java, sqlite3 since command line troubleshooting

my name is Omar
i am following the instructions in this webpage https://www.tutorialspoint.com/sqlite/sqlite_java.htm in order to compile a sample program of java conected with sqlite3.
sample program
import java.sql.*;
public class SQLiteJDBC {
public static void main( String args[] ) {
Connection c = null;
try {
// Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
i downloaded the sqlite connector sqlite-jdbc-3.7.2.jar but according to the webpage above, i Added the address of downloaded jar file sqlite-jdbc-(VERSION).jar in my class path(the same class path of mysql address connector) and place the sqlite-jdbc-3.7.2.jar in C:\Program Files\Java\jdk1.8.0_152\jre\lib\ext just like mysql connector driver.
but i got bad results when i try to run it in command line
"No suitable driver found for jdbc: sqlite: test.db"
i run java -classpath ".;sqlite-jdbc-3.7.2.jar" SQLiteJDBC with the sqlite-jdbc-3.7.2.jar in the same folder in command line but i got bad results too.
"No suitable driver found for jdbc: sqlite: test.db"
Where sqlite-jdbc-3.7.2.jar connector should be placed according to connect java and sqlite just as myql do?
anyhelp is appreciated
thank you in advance
Omar
You should download and use the newest SQLite driver 3.27.2.1 from this site: https://bitbucket.org/xerial/sqlite-jdbc/downloads/
I tried it with 3.7.2 and got the same error. But with 3.27.2.1 it works well.

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

how to link java and mysql

I created a database from the command line and wrote Java code to access the database. My code prints an error on execution. Can anyone tell me how to connect the JDBC driver with Java?
import java.sql.*;
class Test{
public static void main(String arg[]){
try{
String query="select * from photo ";
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost/mydb","user","password");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery(query);
rs.next();
String sname=rs.getString(2);
System.out.println(sname);
con.close();
}
catch(Exception e)
{
System.out.println("error ");
}
}
}
First of all remove the space at the end of the query
String query="select * from photo ";
Next try giving the port in the url
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
Finally as you said its giving you java.lang.ClassNotFoundException:com.mysql.jdbc.Driver
you need to add the mysql-connector.jar in your classpath.Get the jar from here
Well if you are using command prompt you can run like this
java -cp .;completePathOfMysqlConnector/mysql-connector-java-5.1.6.jar className
If you are using elipse then download the jar and add it to the classpath like this
Right click on the project -> properties ->java build path ->switch to libraries tab -> add external jar then select the jar and ok you are done
1>it seems that SQL port is not assigned (default is 3306) in "jdbc:mysql://localhost"
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password");
2> should download and add mysql-connector-java to library
Hope this would help

Derby Embedded with jar file throw database not found exception

Hi i created a derby embedded db with a simple java application.
When test run on eclipse it run perfectly.And then i export as a runnable jar file .Run via cmd
gives exception database not found..!!!
public class Main {
public static void main(String[] args) throws SQLException {
final String driver="org.apache.derby.jdbc.EmbeddedDriver";
final String url="jdbc:derby:db/testdb";
try {
Class.forName(driver);
Connection connection=DriverManager.getConnection(url);
//connection.createStatement().execute("create table channels(channel varchar(20),topic varchar(20))");
// connection.createStatement().execute("insert into channels (channel,topic) values('hbo','action')");
// System.out.println("saved");
PreparedStatement preStmt=connection.prepareStatement("select * from channels");
ResultSet set=null;
set=preStmt.executeQuery();
while(set.next()){
System.out.print(set.getString(1));
System.out.println(set.getString(2));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Errors
Exception in thread "main" SQL Exception: Database 'db/testdb' not found.
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Sourc
My need is when i run jar file on other java enabled pc it must run..!!!
i already tried on other pc it gives me same error..!
How can i make database created....!!
Someone know please help..!
After building the jar, go to the project folder and copy the dist folder. Move it to a new location and also copy the database folder inside the new dist folder you just moved. That should do it; most of the time when people have problem with Derby it is because of Java file paths.
The magic about Derby schema creation is via jdbc url itself.
Let me use Java 8 Derby to elaborate. Run cmd.
Add Derby related to environment path:
cd D:\Project\derbydb
set JAVA_HOME=C:/Program Files/Java/jdk1.8.0_92
set DERBY_HOME=C:/Program Files/Java/jdk1.8.0_92/db
set PATH=%PATH%;%DERBY_HOME%/bin
Execute ij command to work with Derby.
D:\Project\derbydb>ij
ij version 10.11
ij> CONNECT 'jdbc:derby:testdb;create=true';
When url="jdbc:derby:testdb;create=true", [D:\Project\derbydb\testdb] folder is automatically initialized from where it is run. Then, we can use Derby normally like any other databases.
ij> CREATE TABLE cart (
item VARCHAR(50),
price DECIMAL (10,5),
dt TIMESTAMP,
primary key (item)
);
ij> select * from cart;
After Derby repository exists, then we can connect it from anywhere.
C:\Users\oraclesoon>ij
ij version 10.11
ij> CONNECT 'jdbc:derby:D:\\Project\\derbydb\\testdb';
ij> select * from cart;

Categories