How to perform J2ME Database connection?
J2ME is known as Java 2 Micro Edition. It is Java version of Sun which is highly suitable for machines having limited hardwares like mobiles, PDAs and electronic devices. It can even work at 128 KB RAM. MIDP that is Mobile Information Device Profile is a profile for mobiles, cellular phones and pagers etc. Database is required for most of the applications whether it is web application or wap application or any J2ME application. But unfortunately CLDC frameworks do not support JDBC APIS.
JDBC is Java Database Connectivity which is used to make connection between Java and Database. In order to perform J2ME Database Connection to devices having CLDC configuration, it is required to call some Servlet from the MIDLet. All the coding with the connection to database, running of queries and all other functionalities are needed to be done in Servlet itself. MIDLet can be used to pass the parameters to servlet like username and password.
If you are looking help in Canvas Programming, please get introduced to it on J2ME Canvas Programming
Get more details about J2me Midlet Tutorial
Here we will try to perform the J2ME Database Connection.
The programs below will take the name of database, username as well as password from the MIDLet executing on some J2ME device and will pass the parameters to the Servlet. Then the status of connection is returned to the MIDLet.
import java.io.*;
import java.util.*;
import javax.microedition.midlet.*; // package required for J2ME
import javax.microedition.lcdui.*; // package required for J2ME
import javax.microedition.io.*; // package required for J2MEpublic class MySQLConnection extends MIDlet implements CommandListener {
private String username;
private String url = “http://localhost:8080/connect/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 MySQLConnection() throws Exception {
display = Display.getDisplay(this);
}
public void startApp() {
displayMenu();
}
public void displayMenu() {
menu = new Form(“Connect to Database”);
tb = new TextField(“Please enter database: “,”",30,TextField.ANY );
tb1 = new TextField(“Please enter username: “,”",30,TextField.ANY);
tb2 = new TextField(“Please enter 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 back 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 will take input from user like db,user and pwd and will pass to the 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);
}
};
}
Above program is the MIDLet programwhich has three textfields to enter database, username and password for the connection to be made. When user enters the database name, username and password, all the parameters will be passed to the following servlet. This servlet will make connection with the database specified in the database name parameter having username and password that it gets from the MIDLet program. After making connection it returns the connection status which is displayed by the MIDLet program.
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 is used to connect to MYSQL database*/
private void connect (String db, String user,String pwd) throws Exception {
// Establishing 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);
}
}
In this way indirectly you can perform the J2ME database connection very easily. You can test the above example application in any simulator for sending database connection from simulator on PC to database. After the successful testing on the Simulator you can run it on any mobile device.
Learn how to make a Signed MidLet in J2ME : J2ME Midlet

August 27th, 2010
admin
Posted in
Tags: 


A very well written article on the topic.
As a matter of a fact this is not news for me. But still thanks to the author.
I will add your site to favorites. Great work!
Thank you all for your information and comments Regards ….
Thanks a lot for sharing this with all of us you really know what you’re talking about! Bookmarked. Please also visit my site =). We could have a link exchange agreement between us!
СайтMuzOn.In где можно заказать качественную,оригинальную,качественную вещь от наших дизайнеров.Любые темы и направления,разнообразный выбор футболок,кепок,кружек,значков и т.д есть все по разумной цене.Site MuzOn.In where you can order high-quality, original, high-quality item from our dizaynerov.Lyubye topics and areas, a diverse selection of shirts, caps, mugs, badges, etc. there are all at a reasonable price
Very nice impressive blog long time looking for. my guide for my web
Hey There. I found your blog using msn. This is a really well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely comeback.
Great explanantion for the SQL connection… A very nice and cool video explanation… would also want to know how to load it to the phone and run the app tutorial… also for android cellphone how would we run the app