Question

I want to compare the databases fetched into a ResultSet object with a database stored in properties file.If the database match with dbname of properties file it will print xxx.I am providing the code below.

public static void main(String[] args) throws IOException, ClassNotFoundException,   SQLException {
Properties props=new Properties();
props.load(new FileInputStream("/home/core/Desktop/Java/Sample Netbeans   Projects/Project/PropStoreDb/StoreDbNameProps.properties"));        
Class.forName(props.getProperty("db.driver"));
Connection con= DriverManager.getConnection("jdbc:mysql://localhost/", "root", "");
Statement st = con.createStatement();
    ResultSet rs = st.executeQuery("show databases");
    if(rs.next()){
        for(int i=1;i<=rs.getRow();i++){
            if(rs.getString(i).equals(props.getProperty("db.dbname")))
            {
                System.out.println("xxx");
            }
        }
    }

Here is the properties file

db.dbname=mydb
db.url=jdbc:mysql://localhost/mydb
db.driver=com.mysql.jdbc.Driver
Was it helpful?

Solution

Change the code to

while(rs.next()){
if(rs.getString(1)!=null && rs.getString(1).equals(props.getProperty("db.dbname")))
            {
                System.out.println("xxx");
            }
}

There is no need of a for loop. The query show databases; will return a resultset with a single column.so, you can get the data using rs.getString(1) since column id starts from 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top