Saturday, February 28, 2009

DataBase Connection Using J2ME

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 MySQLConn 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;
      DBConn db;

      public MySQLConn() 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 DBConn(this);
                  db.start();
                  db.connectDb(tb.getString(),tb1.getString(),tb2.getString());
            }
      }

      public class DBConn implements Runnable {
            MySQLConn midlet;
            private Display display;
            String db;
            String user;
            String pwd;
            public DBConn(MySQLConn 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 = (HttpConnection) Connector.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 response) throws 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 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);
      }
}

87 comments:

  1. I used above both the programs. But the above programs are successful when you send the data from pc i.e. simulator to the database. But when you configure the above programs on mobile handset of sony ericsson K750i then they are not working properly. Please tell me what should I do?

    ReplyDelete
    Replies
    1. Hey Sachin,I am not able to run the code for a simulator itself.
      I wonder what am I doing wrong.Could you please guide me here..really need some help..

      Delete
    2. i have a same problem please tell me sachin how to connect the database in j2me

      Delete
  2. sachin i have a similar problem. i wnat to send data from a form i created in net beans to a database how is that possible. thanks

    ReplyDelete
  3. if u did not change ne thing in the above code then, i suppose u have to change the url in the j2me code to point to the servlet

    ReplyDelete
  4. can smbody help me
    How to execute this program?
    where to put servlet file?

    ReplyDelete
    Replies
    1. this code is for midlet not for servlet
      hahahahahahaha.....................................

      Delete
  5. sachin i want to execute this program on my pc only can u help me thanks in advance

    ReplyDelete
  6. Please help us tell us everything you need to do to get this baby running step by step :)

    ReplyDelete
  7. some securtiy related issues (like signing your jar with appropriate certificate from a certificate issuer) can cause that, because your http call may be marked as UNTRUSTED if your jar is not a trusted one (unsigned)

    ReplyDelete
  8. plz help me,how to execute above program in pc.i am not getting the thing.thanks.

    ReplyDelete
  9. please help me in executing this program step by step?

    ReplyDelete
  10. Dude i guess localhost make u trouble!

    ReplyDelete
  11. i think you must setting the NAT/port forwarding on your router

    ReplyDelete
  12. Guys I am in trouble, Plz Help Me out.
    Where can i put the import java.sql.*;
    And How can i connect to JDBC.
    Plz Help me out.

    If any Body help me plz Mail me at
    nitinverma274@gmail.com

    ReplyDelete
  13. how to run the above code pl any one tell.........

    ReplyDelete
  14. hi friends plz help in executing the above database program....

    It was executing correctly but it is showing java.io.EOFException
    how to eleminate that exception

    ReplyDelete
  15. pavan PM me at sun.ccna@gmail.com

    ReplyDelete
  16. Guys you have to put the ServeLet code on a public web site and need to change the url to that web site.

    ReplyDelete
  17. hi i have connected to database but i am not able to print on emulator so can any one help me thanks in advance

    ReplyDelete
  18. iam able to connect remotedatbase through servlet which is running on the local machine.how to give url of servlet which is running on the remote server.......plz help me

    ReplyDelete
  19. pls help me in running this program...
    i m just a beginner...
    i got netbeans6.9....
    my questions are...
    1.how to add mysql into it...
    2.how to run the above program....

    pls help me out..

    ReplyDelete
  20. how to run the above program........?

    ReplyDelete
  21. just create a midlet in netbeans and then
    write a servlet application individually
    that gives you a addree like
    "http://localhost:8080/MyApplication/getConnetion"
    give that in this Midlet code.
    I think it works

    ReplyDelete
  22. No one has still explained how to run this program step by step,plz do it,if someone has tried

    ReplyDelete
  23. Hi. I just create below a midlet code in eclipse and then shown me error "Connector class not found at Line 80". now, How do it? please help me.

    ReplyDelete
  24. ayre bel neswen chou hal fachal ento. rouho l3abo be gher mahal

    ReplyDelete
  25. BIG TRASH.. can't be implemented!

    ReplyDelete
  26. m having the creation of this j2me how i can switch it to j2me form to java ????
    weather i have to link tow pages??plesae send the snapshot

    ReplyDelete
  27. this code is working on emulator but i m not able to find how to connect with the mobile, can anybody reply that how can i do that. please reply

    ReplyDelete
    Replies
    1. How?Pls help me..I can't get this thing to run on my emulator...pls help

      Delete
  28. can any buddy tell me how to write these progs
    i known about j2me but where i have to start that another code should i start please help me out thanks

    ReplyDelete
  29. hi frnz pl explain the above code to execute

    ReplyDelete
  30. hi jason just copy and paste it in netbeans
    it only work on nokia handsets

    ReplyDelete
  31. hi frndz any body can help to save data in sdcard.
    im geting data through bluetooth i need to save dat data in my mobile(Nokia) sdcard

    if nay body knows pls send code to my mail id
    baldevswamy@yahoo.co.in

    ReplyDelete
  32. hi frnz i am doing projet on mobileBanking. i hav the code and i can run it using the emulator.But i don no how to run this code using mobile.

    if any 1 knows plzz reply me..at
    jalander.raju@gmail.com

    ReplyDelete
  33. Murugan,
    hi am working for j2me nokia c1-02 device.I want record in amr format and upload to mysql database so i have the code for recorder now i want know how to upload to server ....Please help anyone...murugacse4@gmail.com

    ReplyDelete
  34. when i compile combined prog in net beans ide
    im get error like
    Error preverifying class java.lang.Class
    VERIFIER ERROR java/lang/Class.newInstance0()Ljava/lang/Object;:
    Illegal type in constant pool
    Preverification failed with error code 1
    can any one give solution pls...

    ReplyDelete
  35. please help me in executing this program step by step? am new to this one i dont know how to excecute..

    ReplyDelete
  36. can anybody,let me know any j2me data-base book.

    ReplyDelete
  37. you guys you need to explain to us what we need to change in order to run this staff

    ReplyDelete
  38. please i want to know how to retrieve data from servlet to j2me.

    please reply.

    tokjohn@yahoo.com

    ReplyDelete
  39. code explanation anyone!!!

    ReplyDelete
  40. For this example to work do you running server etc to make it work when you compile the file in mobile phone format within J2Me file

    ReplyDelete
  41. where should i place the servlet file. i m please help me.

    ReplyDelete
  42. i got error . i need how to run . im using netbeans IDE 7 . can i connect j2me with mysql via netbeans ??

    ReplyDelete
  43. hi all, i'm a j2me learner writing a project that requires mysql database connectivity. can anyone please send mysql-j2me database-connectivity notes/tutorials?????-reply at kimotho.dennis@yahoo.com

    ReplyDelete
    Replies
    1. did u find the connectivity code..i am in a similar problem

      Delete
  44. The example runs perfectly using Netbeans 7.0.1. I probe it in my Nokia N97 and runs. Anybody who needs help write me mastudily@yahoo.es

    ReplyDelete
  45. Java Rezalet Kafa siken bir dil.Hala anlamış değilim millet niye bu kadar bu dilin üzerinde yoğunlaşmış kafayı yiyorum
    Delphinin eline değil Bokuna bile su dökemez
    Siktiğimin Javası

    ReplyDelete
  46. i also want to connection with database and j2me Application ....Plz tell me How can i do?????


    Contact me:-Sajidqadri91@yahoo.in

    ReplyDelete
  47. Guys pls help me too,i'm using netbeans too and i made my own j2me file its running bt now i want to access database so i need servlet bt i don't know where to place the servlet file,pls help me i need to complete my project...
    pls contact me at jason_joseph60@yahoo.com

    ReplyDelete
  48. I can not working with "HttpServlet" how can i do?

    ReplyDelete
  49. hi all, i'm a j2me learner writing a project that requires mysql database connectivity. can anyone please send mysql-j2me database-connectivity notes/tutorials?????-reply sumit_clarck@yahoo.co.in

    ReplyDelete
  50. Hello could someone please tell me how to set the server up on windows and the sql database and email me please to. warstu@gmail.com

    ReplyDelete
  51. hi all, i'm a j2me learner doing a project that requires mysql database connectivity. anyone wiling to help me with the database would be paid a good money. contact me please: d.jooje@yahoo.com

    ReplyDelete
  52. could you anybody help me to connect servlet with j2me.this code gives exception request resourse is not avilable.i m working with netbeans7.1.

    ReplyDelete
    Replies
    1. Hey,It is happening because your servlet cannot communicate with the mysql database.Make sure XAMPP/WAMP is on..
      Or try running the servlet code individually to extract data from the MYSQL db.

      Hey I am working on a project htat involves j2me servlet and mysql..I have had the similar problems..but I solved most of them...contact me so we can chat and collaborate resources

      Delete
    2. thank you for your reply.i can run now j2me with servlet . but what a problem know , its working in netbeans using emulator.not working in nokia mobile .it returns -34 like that what have to do. pls help me.

      Delete
    3. Mr SAGAR J , i need your help. liza_5757@yahoo.com

      Delete
    4. Yes?Pls mail me directly or rply to this post..

      Delete
    5. what help u want.

      Delete
  53. I SEARCHED DATA FROM A TABLE AND CLICKED BACK BUTTON TO SEARCH ANOTHER DATA FROM SAME TABLE.BUT IT IS SHOWING SAME DATA IN ON TOP OF NEW SEARCHED DATA.

    HOW TO CLEAR LAST APPENDED DATA FROM FORM.

    ReplyDelete
    Replies
    1. Now I have solved this problem by using deleteAll() method

      Delete
    2. Can you give me good approach to retrieve bulk amount of data from database???

      Delete
  54. any possible to add swing class to j2me or anyway is available to design a form in j2me

    ReplyDelete
    Replies
    1. Well you cannot use swing directly. But you can use the swing approach to JavaME. The project is known as LWUIT. Try googling it. Read the tutorial. If you find the tutorial too hard to understand, search for the video tutorial in YouTube.

      Delete
  55. I have run the program and its working. How to get the values from database and display it on to the mobile screen??

    ReplyDelete
  56. venkat please display your working code here

    ReplyDelete
  57. i put java file in netbeans and servlet file in my domain with working java hosting...but i am getting a page with html codings .. error 411 nginx...how to solve it.....

    ReplyDelete
  58. just tried it with php..works smoothly..and more reliable...
    heres a sample code
    http://thinkdiff.net/j2me/communication-between-j2me-client-and-php-page-in-server/

    ReplyDelete
    Replies
    1. mr sagar, can u help to use this code step by step? and what is the name of database and table should i creat in sql. pleasee, i'm a beginner :)

      Delete
  59. I have run the program and its working. How to get the values from database and display it on to the mobile screen?

    Email ID: mr.vipintyagi@gmail.com

    ReplyDelete
  60. guys i just copied this code i am going to try this. i am beginner in j2me. i post now just because to come in the contact of experts like you all...

    ReplyDelete
  61. i have copied this code and whenever i do login it showing me 0 why???
    please someone help me.
    Thanks
    android.amitsuri@gmail.com

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  62. I have done the required changes and now my application is working fine......

    ReplyDelete
    Replies
    1. how do you create, execute the servlet.. i need the step by step guideline... i use netbeans 6.9

      Delete
  63. hello, can anyone please explain this to me step by step on how to do it ? im a beginner and this is my first time using netbeans. please help. email me : adilaazman@hotmail.com

    ReplyDelete
  64. Do you know what Einstein said? "If you cant explain it simply, you don't understand it well enough." this program is good if it is explained step by step in order how to write j2me in one side and servlet in the other side. due to it lacks the above specifications this program is a big headache to me.
    please don't post such a thing if u too don't understand it very well.

    ReplyDelete
  65. Hey guys i got the right solution for the above problem thanks for your help

    ReplyDelete
  66. thank you guys, you were a great help.

    ReplyDelete
  67. hi to all ........... i am developing mobile based attendance management and tracking system, and iam using j2me application integrated with Netbeans IDE so now i wants to connect mobile application with mysql database using GPRS/wifi Connectivity is there any one who help me .... please help me as soon as possible

    ReplyDelete