CLDC framework, do not support JDBC APIS. To connect to databases from devices that have CLDC configuration, you can call a Servlet from MIDLets. Connection to database, running the queries and other functionalities need to be implemented in the Servlet. Passing the parameters to servlet like username, password can be done from MIDLets.
The example below takes database name, username and password from MIDlet running on the J2ME device and passes it to the Servlet. The status of connection is passed to MIDlet:
// Get the response from the servlet page. DataInputStream is =(DataInputStream)c.openDataInputStream(); //is = c.openInputStream(); int ch; sb = new StringBuffer(); while ((ch = is.read()) != -1) { sb.append((char)ch); } showAlert(sb.toString()); is.close(); c.close(); } catch (Exception e) { showAlert(e.getMessage()); } } /* This method takes input from user like db,user and pwd and pass to servlet */ public void connectDb(String db,String user,String pwd) { this.db = db; this.user = user; this.pwd = pwd; }
/* Display Error On screen*/ private void showAlert(String err) { Alert a = new Alert(""); a.setString(err); a.setTimeout(Alert.FOREVER); display.setCurrent(a); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response); }
/* This method connects to MYSQL database*/ private void connect(String db, String user,String pwd) throws Exception {
// Establish a JDBC connection to the MYSQL database server. //Class.forName("org.gjt.mm.mysql.Driver"); Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/"+db,user,pwd);
// Establish a JDBC connection to the Oracle database server. //DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); //Connection conn = DriverManager.getConnection( // "jdbc:oracle:thin:@localhost:1521:"+db,user,pwd);
// Establish a JDBC connection to the SQL database server. //Class.forName("net.sourceforge.jtds.jdbc.Driver"); //Connection conn = DriverManager.getConnection( // "jdbc:jtds:sqlserver://localhost:1433/"+db,user,pwd); } }