java left logo
java middle logo
java right logo
 

Home arrow Java ME Tips
 
 
Main Menu
Home
Java Tutorials
Book Reviews
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Java Network
Java Forums
Java Blog




Most Visited Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews
Top Rated Tips
Java SE Tips
Java ME Tips
Java EE Tips
Other API Tips
Java Applications
Java Libraries
Java Games
Book Reviews


Statistics
Registered Users: 3936
Java SE Tips: 614
Java ME Tips: 202
Java EE Tips: 183
Other API Tips: 779
Java Applications: 298
Java Libraries: 209
Java Games: 16
Book Reviews:
 
 
 
Connecting to databases like Mysql, SQL Server or Oracle on J2ME devices E-mail
User Rating: / 141
PoorBest 

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:

import java.io.*;
import java.util.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;

public class testMySQL extends MIDlet implements CommandListener {
    private String username;
    private String url = 
        "http://localhost:8080/servlets-examples/servlet/getConnection";
    
    private Display display;
    private Command exit = new Command("EXIT", Command.EXIT, 1);;
    private Command connect = new Command("Connect", Command.SCREEN, 1);
    private TextField tb;
    private Form menu;
    private TextField tb1;
    private TextField tb2;
    DB db;
    
    public testMySQL() throws Exception {
        display = Display.getDisplay(this);
        
    }
    
    public void startApp() {
        displayMenu();
    }
    
    public void displayMenu() {
        menu = new Form("Connect");
        
        tb = new TextField("Please input database: ","",30,
                TextField.ANY );
        
        tb1 = new TextField("Please input username: ","",30,
                TextField.ANY);
        
        tb2 = new TextField("Please input password: ","",30,
                TextField.PASSWORD);
        
        menu.append(tb);
        menu.append(tb1);
        menu.append(tb2);
        menu.addCommand(exit);
        menu.addCommand(connect);
        menu.setCommandListener(this);
        display.setCurrent(menu);
    }
    
    public void pauseApp() {}
    
    public void destroyApp(boolean unconditional) {}
    
    public void commandAction(Command command, Displayable screen) {
        if (command == exit) {
            destroyApp(false);
            notifyDestroyed();
        else if (command == connect) {
            db  = new DB(this);
            db.start();
            db.connectDb(tb.getString(),tb1.getString(),tb2.getString());
        }
    }
    
    public class DB implements Runnable {
        testMySQL midlet;
        private Display display;
        String db;
        String user;
        String pwd;
        public DB(testMySQL midlet) {
            this.midlet = midlet;
            display = Display.getDisplay(midlet);
        }
        
        public void start() {
            Thread t = new Thread(this);
            t.start();
        }
        
        public void run() {
            StringBuffer sb = new StringBuffer();
            try {
                HttpConnection c = (HttpConnectionConnector.open(url);
                c.setRequestProperty(
                   "User-Agent","Profile/MIDP-1.0, Configuration/CLDC-1.0");
                c.setRequestProperty("Content-Language","en-US");
                c.setRequestMethod(HttpConnection.POST);
                
                DataOutputStream os = 
                        (DataOutputStream)c.openDataOutputStream();
                
                os.writeUTF(db.trim());
                os.writeUTF(user.trim());
                os.writeUTF(pwd.trim());
                os.flush();
                os.close();
                
                // 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);
        }
        
    };
}
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class getConnection extends HttpServlet {
    
    public void init() {
    }
    
    public void doPost(HttpServletRequest request,
            HttpServletResponse responsethrows ServletException, 
            IOException {
        
        DataInputStream in = new DataInputStream(
                (InputStream)request.getInputStream());
        
        String db = in.readUTF();
        String user = in.readUTF();
        String pwd = in.readUTF();
        
        String message ="jdbc:mysql://localhost:3306/"+db+","+user+","+pwd;
        try {
            
            connect(db.toLowerCase().trim(),user.toLowerCase().trim()
                    pwd.toLowerCase().trim());
            
            message += "100 ok";
            
        catch (Throwable t) {
            message += "200 " + t.toString();
        }
        response.setContentType("text/plain");
        response.setContentLength(message.length());
        PrintWriter out = response.getWriter();
        out.println(message);
        in.close();
        out.close();
        out.flush();
    }
    
    public void doGet(HttpServletRequest request,
            HttpServletResponse responsethrows 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);
    }
}


 Related Tips

 
< Prev   Next >

Page 1 of 0 ( 0 comments )

You can share your information about this topic using the form below!

Please do not post your questions with this form! Thanks.


Name (required)


E-Mail (required)

Your email will not be displayed on the site - only to our administrator
Homepage(optional)



Comment Enable HTML code : Yes No



 
       
         
     
 
 
 
   
 
 
java bottom left
java bottom middle
java bottom right
RSS 0.91 FeedRSS 1.0 FeedRSS 2.0 FeedATOM FeedOPML Feed

Home - About Us - Privacy Policy
Copyright 2005 - 2008 www.java-tips.org
Java is a trademark of Sun Microsystems, Inc.