database result are not showing in java - java

I typed this code but no record is coming from database...I have attached Ms Access database
Need help please...
the output only says "build successful".
import java.sql.*;
public class Db {
Connection con;
Statement st;
ResultSet rs;
//constructor
public Db(){
connect();
}
//connect funtion
public void connect(){
try {
String driver;
driver = "sun.jdbc.odbc.JbdcObdcDriver";
Class.forName(driver);
String db;
db="jbdc:obdc:db2";
//connectin to db
con=DriverManager.getConnection(db);
String sql;
sql="Select * from Table1";
rs=st.executeQuery(sql);
while (rs.next()){
String fname=rs.getString("FirstName");
String lname=rs.getString("LastName");
String age=rs.getString("age");
System.out.println(fname+" "+lname+" "+age);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
// TODO code application logic here
}
Db d=new Db();

Related

Connection closed error - MySQL , JDBC and Hikaricp

Have implemented a DAO pattern with Hikari connection pool
Made the best use of the DAO design pattern.
Have created singleton class which returns the object of a class with a public connection if the object of the singleton class is NULL> object is again created thereby getting the connection
queries to call the static method of the singleton class to obtain public connection and prepared statements are closed in try-with-resources.
application is live for more than 12hrs after few requests queries are not getting executed
"The connection is closed."
public class DatabaseConnection {
//Constants
String url = "jdbc:mysql://localhost:3306/";
String driver="com.mysql.jdbc.Driver";
String userName = "root";
String password = "#";
private static HikariDataSource dataSource;
public Connection conn;
public static DatabaseConnection db;
/**
* A static method which uses HikariDataSource Connection Pooling library to connect with the MySQL Database.
* Accepts and Sets few JDBC details like User Name,Password,URL,Driver Name and many more.
* #return This methods returns HikariDataSource
* #throws SQLException and CasbnException
*/
public DatabaseConnection() throws SQLException,CasbnExceptions {
try {
//create the object of HikariDataSource
dataSource=new HikariDataSource();
//set up the JDBC details (username,password,url,driver)
System.out.println("Inside DatabaseConnection constructor..");
dataSource.setDriverClassName(driver);
dataSource.setJdbcUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(password);
this.conn=dataSource.getConnection();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static DatabaseConnection getCon() throws CasbnExceptions, SQLException
{
if(db==null)
{
System.out.println("Inside getCon() and if block...");
db=new DatabaseConnection();
}
return db;
}
}
public class DAO_Implementation implements DAOFactory {
//Declare all the SQL queries as private static and final
//getCompany query
private static final String getCompanyName="SELECT company_name FROM #.company_register where email=?";
#Override
public String getCompanyName(String Email) throws SQLException {
try
(PreparedStatement pst = DatabaseConnection.getCon().conn
.prepareStatement(getCompanyName)){
pst.setString(1, Email);
ResultSet rs = pst.executeQuery();
rs.next();
Name=rs.getString(1);
}
catch(Exception e)
{
e.printStackTrace();
}
return Name;
}
#Override
public Pojos Individual_Company_detail(String CompanyName) throws SQLException{
try
(PreparedStatement pst = DatabaseConnection.getCon().conn
.prepareStatement(CompanyDetail);){
pst.setString(1, CompanyName);
ResultSet rs = pst.executeQuery();
if(rs.next()==true)
{
Pojos Po=new Pojos();
Po.setCompanyID(rs.getInt(1));
Po.setUserCount(rs.getInt(2));
Po.setPlan(rs.getString(3));
Po.setDateofSub(rs.getString(4));
Po.setSubscriptionID(rs.getString(5));
Po.setVaildTill(rs.getString(6));
return Po;
}
else
{
Pojos Po=new Pojos();
Po.setErrorMessage(CompanyName +" Has not registered to of our Plan and no Recent Transactions");
return Po;
}
}
}
Currently you are returning the same connection all the time using .conn
remove conn from DatabaseConnection and add a different method which getConnection from Hikari datasource every time
This way Hikari will handle connection pooling
public static Connection getConnection() {
return dataSource.getConnection();
}
And open Connection resource separately so it will be closed:
try
(Connection conn = DatabaseConnection.getConnection();
PreparedStatement pst = conn.prepareStatement(CompanyDetail))
public class DatabaseConnection {
String url = "jdbc:mysql://localhost:3306/";
//String dbName = ""
String driver="com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
private static HikariDataSource dataSource;
public static DatabaseConnection db;
public DatabaseConnection() throws SQLException,CasbnExceptions {
try {
//create the object of HikariDataSource
dataSource=new HikariDataSource();
//set up the JDBC details (username,password,url,driver)
System.out.println("Inside DatabaseConnection constructor..");
dataSource.setDriverClassName(driver);
dataSource.setJdbcUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(password);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException
{
if(db==null)
{
db=new DatabaseConnection();
}
return dataSource.getConnection();
}
}

JAVA; How to make SQL getConnection(); as main variable / prime?

I would like to ask how to make Connection con = getConnection(); becaome a primer or main variable so that it would not connect to SQL database every function made. Because as you can see on my codes, every function/class has Connection con = getConnection(); so it connects to the database every function. It makes my program process slowly. Please help thank you.
package march30;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
public class sqltesting {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
get();
}
public static void lookup() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
ResultSet result = statement.executeQuery();
if (result.next()) {
System.out.println("First Name: " + result.getString("first"));
System.out.println("Last Name: " + result.getString("last"));
}
else {
System.out.println("No Data Found");
}
} catch (Exception e) {}
}
public static ArrayList<String> get() throws Exception{
try {
Connection con = getConnection();
PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");
ResultSet result = statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while (result.next()) {
System.out.print(result.getString("first"));
System.out.print(" ");
System.out.println(result.getString("last"));
array.add(result.getString("last"));
}
System.out.println("All records have been selected!");
System.out.println(Arrays.asList(array));
return array;
} catch (Exception e) {System.out.println((e));}
return null;
}
public static void update() throws Exception{
final int idnum = 2;
final String var1 = "New";
final String var2 = "Name";
try {
Connection con = getConnection();
PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
updated.setString(1, var1);
updated.setString(2, var2);
updated.setInt(3, idnum);
updated.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Update Completed");
}
}
public static void delete() throws Exception{
final int idnum = 7;
try {
Connection con = getConnection();
PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
deleted.setInt(1, idnum);
deleted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Delete Completed");
}
}
public static void post() throws Exception{
final String var1 = "Albert";
final String var2 = "Reyes";
try {
Connection con = getConnection();
PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Insert Completed");
}
}
public static void createTable() throws Exception {
try {
Connection con = getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
create.executeUpdate();
} catch (Exception e) {System.out.println((e));}
finally{
System.out.println("Function Completed");
}
}
public static Connection getConnection() throws Exception{
try {
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
String username = "xxxxx";
String password = "xxxxxx";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
return conn;
} catch (Exception e) {System.out.println(e);}
return null;
}
}
To solve your problem you need to store a Connection object in your sqltesting class as a class member. You then need to reference the Connection object instead of getConnection(). It's also worth mentioning that Connection is a AutoClosable object so you need to close this resource when you're done with it, I.E; on application disposal. You also might want to consider using a connection pooling API like Hikari or C3P0 so you can open and close connections when you need them instead of having 1 open for a long time.
class SQLTesting {
private final Connection connection;
public SQLTesting(Connection connection) {
this.connection = connection;
}
public SQLTesting() {
this(getConnection());
}
// other methods
private Connection getConnection() {
// your method to create connection, rename to createConnection maybe.
}
}

java with ms access not showing database result

I'm trying to connect with MS-Access using java but When I Compile this code it gives me no error and compile fine but it doesn't show any result while the database has records in it, table name and field name are also correct, anyone can please help me that what I'm doing wrong in it.
import java.sql.*;
public class database{
Connection dbCon;
Statement statement;
ResultSet result;
public database(){
connect();
}
public void connect(){
try{
String Driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(Driver);
String Sdb = "jdbc:odbc:students";
dbCon = DriverManager.getConnection(Sdb);
statement = dbCon.createStatement();
String sqlQuery = "SELECT * FROM StudentInfo";
result = statement.executeQuery(sqlQuery);
while(result.next()) {
//String name = result.getString("Studentname");
System.out.println(result.getString("Studentname"));
}
}catch(Exception ex){
}
}
public static void main(String[] args) {
System.out.println("**ACCESS DB CONNECTION**");
new database();
}
}
You are not getting error during execution of program because you are eating exception here:
catch(Exception ex){
}
You should try to print the exception trace to know what is going wrong.
catch(Exception ex){
ex.printStackTrace();
}

JDBC No suitable driver found

I'm trying to make a custom MySQL class in Java but I'm getting a few exceptions, here's my code:
MySQL.java:
package evo.common;
import java.sql.*;
public class MySQL {
private static String hostname;
private static String username;
private static String password;
private static String database;
public MySQL(String host, String user, String pass, String db)
{
hostname = host;
username = user;
password = pass;
database = db;
}
public static void Error(Exception ex)
{
System.out.println("Fatal Error: "+ex.getMessage());
}
public static void SQLError(SQLException ex)
{
System.out.println("Fatal SQL Error: "+ex.getMessage());
}
private static Connection connect()
{
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
} catch(Exception e){
Error(e);
}
String url = "jdbc:mysql://"+hostname+":3306/"+database;
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch(SQLException ex){
SQLError(ex);
}
return conn;
}
public static ResultSet result(String query)
{
Connection conn = connect();
PreparedStatement pst = null;
ResultSet rs = null;
try
{
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
} catch(SQLException ex){
SQLError(ex);
}
return rs;
}
public static void main(String args[]){}
}
Test.java:
package evo.common;
import java.sql.*;
public class Test {
public static void main(String args[])
{
MySQL mysql = new MySQL("localhost", "root", "******", "souljaz");
ResultSet res = mysql.result("SELECT * FROM users");
}
}
When I run Test I get these error messages in the console:
Fatal Error: com.mysql.jdbc.Driver
Fatal SQL Error: No suitable driver found for jdbc:mysql://localhost:3306/souljaz
Exception in thread "main" java.lang.NullPointerException
at evo.common.MySQL.result(MySQL.java:58)
at evo.common.Test.main(Test.java:8)
I'm quite new to Java so help appreciated. thanks.
Download the lastest version of Connector/J and included it in your Classpath. If you are using an IDE this is only a matter of including the jar in your referenced libraries. If you are doing everything by hand, refer to this official guide:
java -cp "bin;lib/mysql-connector-java-5.1.30-bin" evo.common.Test
Update:
In Eclipse: Right click your project in Package Explorer, then:
Properties -> Java Build Path -> Add JARS... (if lib is in the project)
or Add External JARS... (if it is external)

How to insert data into database from the main file?

I've got 2 file in my java project : MysqlConnect and Main .
I want to run query from Main class.It's possible?
This is MysqlConnect file:
public class MysqlConnect {
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public Statement stmt;
public String query = "";
public int rs;
public void crearedatabase() {
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
// System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Baza de date nu a fost creata");
}
}
public void executeSql() {
try {
rs = stmt.executeUpdate(query);
} catch (Exception e) {
System.out.println("Mysql Error");
}
}
}
And this is the Main file:
public class Main {
public static void main(String[] args) throws SQLException
{
MysqlConnect sqlconnect = new MysqlConnect();
sqlconnect.crearedatabase();
sqlconnect.query="INSERT INTO `jdbctutorial`.`persons` (`id`, `nume`, `prenume`, `data`) VALUES (NULL, 'xxxx', 'xxxx', '1990-12-12');";
sqlconnect.executeSql();
}
}
The error(Exception) is on the MysqConnection at the try/catch
rs = stmt.executeUpdate(query);
You assign statement object to a local variable named stmt instead of the object field with the same name.
Replace this
Statement stmt = conn.createStatement();
With this:
this.stmt = conn.createStatement();
this is not necessary here, but it's a good practice to have it there.

Categories