8 Replies Latest reply: Aug 9, 2012 1:27 PM by maheshguruswamy RSS

    Connecting and reading from MySQL

    954674
      I have written previous programs that connect and read entries from MySQL using C#, but I'm sort of new to Java and having trouble doing this. I'm basically trying to connect to the database and only retrieve computer names and nothing else. This is the code I've got so far and can't figure out what I'm doing wrong as I keep getting: Cannot connect to database server.
      public class ComputerCheck 
      {
      
           /**
            * @param args
            * @throws ClassNotFoundException 
            * @throws IllegalAccessException 
            * @throws InstantiationException 
            * @throws SQLException 
            */
           public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException 
           {
                Connection conn = null;
                
                try
                {
                     String url = "jdbc:mysql://servername.domain.uni.edu";
                     String username = "root";
                     String password = "pass";
                     String dbName = "database";
                     
                     Class.forName("com.mysql.jdbc.Driver").newInstance();
                     
                     conn = DriverManager.getConnection(url + dbName, username, password);
                     
                     System.out.println("Database Connection Established");
                     
                     Statement s = conn.createStatement();
                     s.executeQuery("SELECT name FROM table");
                     
                     ResultSet rs = s.getResultSet ();
                     int count = 0;
                     
                     while (rs.next())
                     {
                          String computerName = rs.getString("name");
                          
                          System.out.println("Computer Name: " + computerName);
                          ++count;
                     }
                     rs.close();
                     s.close();
                     System.out.println(count + " rows were retrieved");
                     
                }
                catch (Exception e)
              {
                  System.err.println ("Cannot connect to database server");
              }
                
                conn.close();
      
           }
      
      }
      If anyone has any suggestions that would be great. Thanks