Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Connecting to MySQL database over network, using J2ME

Posted on 2004-03-25
2
2,264 Views
Last Modified: 2013-11-23
Hi,
I have tried and tried to get this to work myself but it has come to the stage that I have given up, I have spend too much time trying to get it to work and my time is running out.  I need to get my midlet to connect to MySQL, I am using a network, basically I have two bits of working code and need to know what to do with the "connection" code in order to make it work with the MIDlet code?  Any ideas on how to get the two to connect and read info from the mySQL database instead of a record store?  Here's the code:


import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
import javax.microedition.lcdui.StringItem;
import java.util.*;
import javax.microedition.io.*;
import java.lang.Object;

public class SearchStreams extends MIDlet implements CommandListener
{
  private Display display;                // Reference to Display object
  private Form fmMain;                     // The main form
  private StringItem siMatch;                             // The matching text, if any
  private Command cmFind;                 // Command to search record store
  private Command cmExit;                 // Command to insert items
  private TextField tfFind;                               // Search text
  private RecordStore rs = null;          // Record store
  static final String REC_STORE = "db_dogs"; // Name of record store

  public SearchStreams()
  {
    display = Display.getDisplay(this);
   
    // Define textfield, stringItem and commands
    tfFind = new TextField("Find", "", 20, TextField.ANY);
    siMatch = new StringItem(null, null);    
    cmExit = new Command("Exit", Command.EXIT, 1);
    cmFind = new Command("Find", Command.SCREEN, 2);

    // Create the form, add commands
    fmMain = new Form("Record Search");
    fmMain.addCommand(cmExit);    
    fmMain.addCommand(cmFind);
 
    // Append textfield and stringItem
    fmMain.append(tfFind);
    fmMain.append(siMatch);

    // Capture events
    fmMain.setCommandListener(this);    

    //--------------------------------
    // Open and write to record store
    //--------------------------------
    openRecStore();   // Create the record store
    writeTestData();  // Write a series of records
  }

  public void destroyApp( boolean unconditional )
  {
    closeRecStore();  // Close record store
  }

  public void startApp()
  {
    display.setCurrent(fmMain);  
  }

  public void pauseApp()
  {
  }

  public void openRecStore()
  {
    try
    {
      // The second parameter indicates that the record store
          // should be created if it does not exist
      rs = RecordStore.openRecordStore(REC_STORE, true );
    }
    catch (Exception e)
    {
      db(e.toString());
    }
  }    
 
  public void closeRecStore()
  {
    try
    {
      rs.closeRecordStore();
    }
    catch (Exception e)
    {
      db(e.toString());
    }
  }

  /*--------------------------------------------------
  * Create three arrays to write into record store
  *-------------------------------------------------*/
  public void writeTestData()
  {
   String[] pets = {"duke - big, goofy golden retriever",
                    "tiger - we found in a field",
                    "spike - loves chasing car tires",
                     "bird - eats seed"};
   boolean[] dog = {true, false, true, false};    
   int[] rank = {2, 0, 1, 3};
 
   writeStream(pets, dog, rank);                    
  }

  /*--------------------------------------------------
  * Write to record store using streams.
  *-------------------------------------------------*/  
  public void writeStream(String[] sData, boolean[] bData, int[] iData)
  {
    try
    {
      // Only add the records once
      if (rs.getNumRecords() > 0)
        return;
     
       // Write data into an internal byte array
      ByteArrayOutputStream strmBytes = new ByteArrayOutputStream();
     
      // Write Java data types into the above byte array
      DataOutputStream strmDataType = new DataOutputStream(strmBytes);
     
      byte[] record;

      for (int i = 0; i < sData.length; i++)
      {
        // Write Java data types      
        strmDataType.writeUTF(sData[i]);    
        strmDataType.writeBoolean(bData[i]);
        strmDataType.writeInt(iData[i]);                
       
        // Clear any buffered data
        strmDataType.flush();

        // Get stream data into byte array and write record
        record = strmBytes.toByteArray();
        rs.addRecord(record, 0, record.length);      

        // Toss any data in the internal array so writes
        // starts at beginning (of the internal array)
        strmBytes.reset();
      }
     
      strmBytes.close();
      strmDataType.close();
    }
    catch (Exception e)
    {
      db(e.toString());
    }
  }
 
  /*--------------------------------------------------
  * Search using enumerator and record filter
  *-------------------------------------------------*/
  private void searchRecordStore()
  {
  try
    {
      // Record store is not empty
      if (rs.getNumRecords() > 0)
      {
        // Setup the search filter with the user requested text
        SearchFilter search =
              new SearchFilter(tfFind.getString());
       
        RecordEnumeration re =
              rs.enumerateRecords(search, null, false);

        // A match was found using the filter        
        if (re.numRecords() > 0)
        {
          // Read from the specified byte array
          ByteArrayInputStream strmBytes =
                new ByteArrayInputStream(re.nextRecord());

          // Read Java data types from the above byte array
          DataInputStream strmDataType =
                new DataInputStream(strmBytes);

          // Show matching result in stringItem component on form          
          siMatch.setText(strmDataType.readUTF());
   
          search.searchFilterClose(); // Close record filter
          strmBytes.close();          // Close stream
          strmDataType.close();       // Close stream
          re.destroy();               // Free enumerator
        }
      }
    }
    catch (Exception e)
    {
      db(e.toString());
    }

  }

  public void commandAction(Command c, Displayable s)
  {
    if (c == cmFind)
    {
      searchRecordStore();
    }
    else if (c == cmExit)
    {
      destroyApp(false);
      notifyDestroyed();
    }
  }  
   
  /*--------------------------------------------------
  * Simple message to console for debug/errors
  * When used with Exceptions we should handle the
  * error in a more appropriate manner.
  *-------------------------------------------------*/
  private void db(String str)
  {
    System.err.println("Msg: " + str);
  }
}

/*--------------------------------------------------
* Search for text within a record
* Each record passed in contains multiple Java data
* types (String, boolean and integer)
*-------------------------------------------------*/
class SearchFilter implements RecordFilter
{
  private String searchText = null;
 
   // Read from a specified byte array
  private ByteArrayInputStream strmBytes = null;

  // Read Java data types from the above byte array  
  private DataInputStream strmDataType = null;

  public SearchFilter(String searchText)
  {
    // This is the text to search for
    this.searchText = searchText.toLowerCase();
  }

  // Cleanup
  public void searchFilterClose()
  {
    try
    {
      if (strmBytes != null)
        strmBytes.close();
      if (strmDataType != null)
        strmDataType.close();
    }
    catch (Exception e)
    {}
  }

  public boolean matches(byte[] candidate)
  {
    String str = null;
   
    try
    {
      strmBytes = new ByteArrayInputStream(candidate);
      strmDataType = new DataInputStream(strmBytes);
     
      str = strmDataType.readUTF().toLowerCase();
    }
    catch (Exception e)
    {
      return false;
    }

    // Look for a match    
    if (str != null && str.indexOf(searchText) != -1)
      return true;
    else
      return false;
  }
}


*********************************************
**********************************************
*********************************************
And here's the connection code:

Connection connection = null;
   
try {
        // Load the JDBC driver
        String driverName ="org.gjt.mm.mysql.Driver";

      // MySQL MM JDBC driver
        Class.forName(driverName);
   
        // Create a connection to the database
        String serverName ="localhost";
        String mydatabase ="mydatabase";
        String url ="jdbc:mysql://" + serverName +  "/" +mydatabase;

      // a JDBC url
        String username ="username";
        String password ="password";
        connection = DriverManager.getConnection(url, username, password);
    }
        catch(ClassNotFoundException e)
    {
        // Could not find the database driver
    }
        catch(SQLException e)
    {
        // Could not connect to the database
    }

******************************************************************************************************************************************************
The network is called macneill

Thank you in advance
Averil
0
Comment
Question by:Averil
2 Comments
 
LVL 3

Accepted Solution

by:
eicheled earned 500 total points
ID: 10682658
What error are you getting? You code sample is incomplete so it is hard to tell. IE - ou call DriverManager.getConnection to set the variable 'connection' but I don't see it used anywhere. Can you give more details about the problem?
0
 

Author Comment

by:Averil
ID: 10812448
I got it working thanks anyhow
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
reverse digits of a number using for loop 5 52
tomcat startup error 5 100
Java: How do I open the default windows program for a given file type 3 38
Chrome and Firefox Java 5 49
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

765 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question