connecting to database(postgres) with java in intellij - java

I want to write a code to get my queries from input and run it and show me the result.I have to connect to database in my code.
I connected to postgres by intellij database extension and my queries run in the console.
but i want to do that in my code(i mean get the queries from user and run it).
is it possible to use this database connection and run queries on it?
i got connected successfully by this code too :
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/db","postgres", "pass");
and i wrote some queries.
all query types(such as update , delete , insert , ...) run and the result is visible in the pgadmin but i want to have the result in my java code

Here is an example to run a query with JDBC. you can download the JDBC here https://jdbc.postgresql.org/download.html and added to your classpath
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class PostgreSqlExample {
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/example", "postgres", "postgres")) {
System.out.println("Java JDBC PostgreSQL Example");
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement();
System.out.println("Reading car records...");
System.out.printf("%-30.30s %-30.30s%n", "Model", "Price");
ResultSet resultSet = statement.executeQuery("SELECT * FROM public.cars");
while (resultSet.next()) {
System.out.printf("%-30.30s %-30.30s%n", resultSet.getString("model"), resultSet.getString("price"));
}
} /*catch (ClassNotFoundException e) {
System.out.println("PostgreSQL JDBC driver not found.");
e.printStackTrace();
}*/ catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}

Related

How to resolve sqlite communication error in java IntelliJ

I'm trying to connect to a sql database with java but this isn't really working out. normally people say they have a user and password but I never created anything like that. I downloaded sqlite studio and you can pretty much just make a database without having to create some kind of account but when i'm trying to connect it gives me an error that it can't connect com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure.
How do I resolve this issue? This is the code I have right now:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class MyJDBC {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/JDBC-video");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from people");
while (resultSet.next()) {
System.out.println(resultSet.getString("firstname"));
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

Accessing Oracle DB express from within Java

I have a basic Java application (with a GUI) that uses a linked list to add/remove/modify Customer objects and I want to store them in a database (Oracle DB express to be exact)?
As I understand it, I have to create a table with some tool, and the use that tool to auto-generate a Java class that would allow me to communicate with the DB. How far off am I with this?
Just to make your question clear, What tool have you used to generate your java code?
I recommend you to avoid using code generation tool in case you want to learn in and out of Java.Here is an example of how you can connect your SWING application with Oracle DB,MySQL,Derby and many more other databases.
Connection con;
Statement smt;
ResultSet rs;
String user="databaseuser";
String pass="password";
String path="jdbc:oracle:thin:#localhost:1521:Sampledb"; //put db url here
try{
con=DriverManager.getConnection(path, user, pass);
smt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
String SQL="SELECT *FROM Registered_users_tb "; //Your Query here
rs=smt.executeQuery(SQL);
rs.moveToInsertRow();
//First param is db column name,second param is variable name
rs.updateString("USERNAME", username);
rs.updateString("FNAME", fname);
rs.updateString("MNAME", mname);
rs.updateString("LNAME", lname);
rs.updateString("GENDER", gender);
rs.updateString("DEPARTMENT", dept);
rs.insertRow();
rs.close();
smt.close();
}
catch(SQLException err){
JOptionPane.showMessageDialog(Classname.this,err.getMessage());
}
For creating a complete new database, oracle provide a gui tool called DBCA. I found a couple of links to use this tool: Link 1 and Link 2
This tutorial teaches how to access an Oracle database. For accessing such an database you need additional drivers found here. Here an short example how to access such a database:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
class DatabaseAccess
{
public static void main(String [] args)
{
Connection connection = null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dbPath = "jdbc:oracle:thin:#localhost:1521:myDatabase";
String username = "user";
String password = "password";
connection = DriverManager.getConnection(dbPath, username, password);
if(connection != null)
{
System.out.println("Connected with database");
Statement statement = connection.createStatement();
ResultSet results = statementt.executeQuery("SELECT * FROM myTable");
while(result.next())
{
System.out.println(result.getString("myString"));
}
}
catch(ClassNotFoundException | SQLException exc)
{
exc.printStackTrace();
}
finally
{
try
{
connection.close();
}
catch(SqlException exc)
{
exc.printStackTrace();
}
}
}
}
For an more advanced example visit the given link.

Hive server not starting

Iam new to the hadoop ecosystem. Tried to access hive through jdbc. For that I have written the following code
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveConnection {
private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000");
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select * from test.employees");
while (res.next()) {
System.out.println(res.getString(1));
} }}
and started the hiveserver2 (hive version 0.12 & hadoop version 1.1.2) through the terminal and im getting the status as "Starting HiveServer" . When i tried executing the above code from eclipse im no getting any error and any results neither(Got the same when i executed the executable "hiveserver" ).
Can any one help me out.
Thanks in advance.
Following ways are most really reason for your problem.
1.Is the hive-jdbc-*.Jar having classpath like this "org.apache.hadoop.hive.jdbc.HiveDriver" or "org.apache.hive.jdbc.HiveDriver"?
2.While connection,you need to pass the user name and password like this?
If you use hive server2 then you have to set the connection like below.
con = DriverManager.getConnection("jdbc:hive2://localhost:10000/default", "", "");
Above ways are really helpful for you.
Thanks in advance.

using a Java DB Connection in another form

I have created a simple Java connection script in Java to connect to a database shown below.
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class dbconn {
public static void main(String[] args) throws ClassNotFoundException
{
Class.forName("org.sqlite.JDBC");
Connection connection = null;
try
{
// create a database connection
connection = DriverManager.getConnection("jdbc:sqlite:C:/Program Files (x86)/Spiceworks/db/spiceworks_prod.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
}
catch(SQLException e)
{
// if the error message is "out of memory",
// it probably means no database file is found
System.err.println(e.getMessage());
}
finally
{
try
{
if(connection != null)
connection.close();
}
catch(SQLException e)
{
// connection close failed.
System.err.println(e);
}
}
}
}
Now I have tested this connection via some SQL queries inside the dbconn script and it works.
However my question is, how would Icall this instance of the database into another form in the same project to preform the same SQL queries which are:
ResultSet resultSet = null;
resultSet = statement.executeQuery("SELECT * FROM users");
while (resultSet.next())
{
System.out.println("EMPLOYEE Email: " + resultSet.getString("email"));
}
You can retain and reuse the Connection, saving it probably in some static field. If you access it from multiple threads, SQLite must work in the Serialized mode. You must have the code somewhere to re-establish the connection if it has been lost for some reason.
If the use of Connection is not heavy, you can also have some method that opens it and close when no longer needed, better inside the finally block.

why No suitable driver found for mysql message here?

this is my code snippet,
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Delete
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("mysql:jdbc://localhost:3306/raja","root","459805");
Statement stmt=con.createStatement();
int count=stmt.executeUpdate("DELETE GENNU WHERE USER_ID=3;");
if(count>0)
System.out.println(" Ok Deletion done");
}
catch(ClassNotFoundException e)
{
System.out.println(e.getMessage());
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
}
}
and when I execute it , i got like this.
actually you have an error in your DELETE statement, you lack FROM keyword. it should be
DELETE FROM GENNU WHERE USER_ID=3
see the error, it's pointing on DELETE.
UPDATE 1
try, jdbc:mysql not mysql:jdbc
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost:3306/raja"
+ "user=root&password=459805");
MySQL and JAVA JDBC
Try with
Class.forName("com.mysql.jdbc.Driver").newInstance();
The documentation says:
// The newInstance() call is a work around for some
// broken Java implementations
Class.forName("com.mysql.jdbc.Driver").newInstance();
Also, the URL should be
jdbc:mysql://localhost/3306/raja
and not
mysql:jdbc://localhost/3306/raja
You need the mySQL Java Connector. Which you can find at the download page here:
https://www.mysql.com/products/connector/

Categories

Resources