Checking if an inserted data from a java program exists in a certain Database

Let's Say I have a Database named Product that has 2 columns with 3 rows

ID, NAME, PRICE

For example if I were to check if something exists in the Database by inputing the object's ID through a java program and i would want it to return the Name. How would the code look like?

1 answer

  • answered 2018-11-08 08:23 Suraj

    import java.sql.*; 
    
    // this code is for oracle database
    
    //download the jar file ojdbc14.jar and add it to your libraries
    
    class OracleDB{  
    public static void main(String args[])throws Exception{  
    
    Class.forName("oracle.jdbc.driver.OracleDriver");    
    
    Connection
    con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
    Statement stmt=con.createStatement();  
    ResultSet rs=stmt.executeQuery("select * from Product");  
    
    while(rs.hasNext()){ 
    System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); 
    } 
    
    con.close();  
    }}  
    
    // below code is for Mysql database
    
    // download file mysql-connector.jar and upload it to your libraries 
    
    import java.sql.*;  
    
    class MysqlDB{  
    public static void main(String args[]){  
    try{  
    
    Class.forName("com.mysql.jdbc.Driver");
    
    Connection con=DriverManager.getConnection( "jdbc:mysql://localhost:3306/xyz","root","root");  
    //here xyz is database name, root is username and password  of database
    
    Statement stmt=con.createStatement();  
    
    ResultSet rs=stmt.executeQuery("select * from Product");  
    
    while(rs.next())  {
    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
    }
    
    con.close();  
    }catch(Exception e){ System.out.println(e);}  
    }  
    }