Click here to Skip to main content
15,913,944 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
package singleton1;

import java.util.Scanner;

public class Database {

	private static Database connection;
	
	static String dbname1="none";
    static String dbpass1="none";
    static String answerYes="y";
    static String answerNo="n";
	static Scanner myObj = new Scanner(System.in); 

	private static Database getInstance(String dbname,String dbpass) {
		if(connection==null) {
			if(dbname!=dbname1 || dbpass!=dbpass1)
    			System.out.println("Connection says: not found connection");

			System.out.println("Connection says: do you wish to recreate a new one,type y for yes and n for no");		
			String answer = myObj.nextLine();

			if(answer==answerYes) { 
				System.out.println("recreation...");
			    connection=new Database();
			}
			else if(answer==answerNo) {
				System.out.println("end connection");
				
			}
	    
    		System.out.println("Connection says:  connected");
		
		}
		return connection;
	}
	
	
	public static void main(String[] args) {
		
 
    Database.getInstance("l", "none");
	}

}


What I have tried:

trying to make db connection which says if the user typed wrong data ,then it asks to create a new database with the typed data
Posted
Updated 16-Apr-21 1:32am
v2
Comments
SeanChupas 15-Apr-21 14:39pm    
Debug the code, walk through it step by step and find out what the problem is. Easy.
Richard MacCutchan 16-Apr-21 5:58am    
That code does nothing useful, except post messages and request a yes or no response. Also, this has nothing to do with the Singleton pattern.

1 solution

That code does not implement the Singleton pattern - it's just a static class. Singleton is different: it allows one single instance of a class which is created via a private constructor to prevent others being created. It's not the same process at all!
See here: Java - How to Use Singleton Class? - Tutorialspoint[^]

And to be honest, your whole approach is wrong: the Database class should not be talking to the user at all; it should have no idea what environment it is working in. It should report problems back to the calling method and let it do the "donkey work" of telling the user.

Plus ... connections strings aren't trivial, and are prone to change - for example, the connection string you use for development had damn well better be different from that you use in production or you are going to get some really severe problems!
Connection strings will be database engine type dependant (the Access engine string will be very different from an SQL Server string for example) so you should be retrieving that from an external config file not even trying to hard code these things.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900