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);
}
}
Subscribe to:
Post Comments (Atom)
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?
ReplyDeleteHey Sachin,I am not able to run the code for a simulator itself.
DeleteI wonder what am I doing wrong.Could you please guide me here..really need some help..
i have a same problem please tell me sachin how to connect the database in j2me
Deletesachin 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
ReplyDeleteif 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
ReplyDeletecan smbody help me
ReplyDeleteHow to execute this program?
where to put servlet file?
sachin i want to execute this program on my pc only can u help me thanks in advance
ReplyDeletePlease help us tell us everything you need to do to get this baby running step by step :)
ReplyDeletesome 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)
ReplyDeleteplz help me,how to execute above program in pc.i am not getting the thing.thanks.
ReplyDeleteplease help me in executing this program step by step?
ReplyDeleteDude i guess localhost make u trouble!
ReplyDeletei think you must setting the NAT/port forwarding on your router
ReplyDeleteGuys I am in trouble, Plz Help Me out.
ReplyDeleteWhere 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
is it working on netbeans? how?
ReplyDeletehow to run the above code pl any one tell.........
ReplyDeletehi friends plz help in executing the above database program....
ReplyDeleteIt was executing correctly but it is showing java.io.EOFException
how to eleminate that exception
pavan PM me at sun.ccna@gmail.com
ReplyDeleteGuys you have to put the ServeLet code on a public web site and need to change the url to that web site.
ReplyDeletehi i have connected to database but i am not able to print on emulator so can any one help me thanks in advance
ReplyDeleteiam 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
ReplyDeletepls help me in running this program...
ReplyDeletei 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..
how to run the above program........?
ReplyDeletejust create a midlet in netbeans and then
ReplyDeletewrite 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
No one has still explained how to run this program step by step,plz do it,if someone has tried
ReplyDeleteHi. 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.
ReplyDeleteayre bel neswen chou hal fachal ento. rouho l3abo be gher mahal
ReplyDeleteBIG TRASH.. can't be implemented!
ReplyDeletem having the creation of this j2me how i can switch it to j2me form to java ????
ReplyDeleteweather i have to link tow pages??plesae send the snapshot
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
ReplyDeleteHow?Pls help me..I can't get this thing to run on my emulator...pls help
Deletecan any buddy tell me how to write these progs
ReplyDeletei known about j2me but where i have to start that another code should i start please help me out thanks
hi frnz pl explain the above code to execute
ReplyDeletehi jason just copy and paste it in netbeans
ReplyDeleteit only work on nokia handsets
hi frndz any body can help to save data in sdcard.
ReplyDeleteim 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
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.
ReplyDeleteif any 1 knows plzz reply me..at
jalander.raju@gmail.com
Murugan,
ReplyDeletehi 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
when i compile combined prog in net beans ide
ReplyDeleteim 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...
please help me in executing this program step by step? am new to this one i dont know how to excecute..
ReplyDeletevhf
ReplyDeletecan anybody,let me know any j2me data-base book.
ReplyDeleteyou guys you need to explain to us what we need to change in order to run this staff
ReplyDeleteplease i want to know how to retrieve data from servlet to j2me.
ReplyDeleteplease reply.
tokjohn@yahoo.com
code explanation anyone!!!
ReplyDeleteFor 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
ReplyDeletewhere should i place the servlet file. i m please help me.
ReplyDeletei got error . i need how to run . im using netbeans IDE 7 . can i connect j2me with mysql via netbeans ??
ReplyDeletehi 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
ReplyDeletedid u find the connectivity code..i am in a similar problem
DeleteThe 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
ReplyDeleteJava Rezalet Kafa siken bir dil.Hala anlamış değilim millet niye bu kadar bu dilin üzerinde yoğunlaşmış kafayı yiyorum
ReplyDeleteDelphinin eline değil Bokuna bile su dökemez
Siktiğimin Javası
i also want to connection with database and j2me Application ....Plz tell me How can i do?????
ReplyDeleteContact me:-Sajidqadri91@yahoo.in
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...
ReplyDeletepls contact me at jason_joseph60@yahoo.com
I can not working with "HttpServlet" how can i do?
ReplyDeletehi 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
ReplyDeleteHello 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
ReplyDeletehi 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
ReplyDeletecould you anybody help me to connect servlet with j2me.this code gives exception request resourse is not avilable.i m working with netbeans7.1.
ReplyDeleteHey,It is happening because your servlet cannot communicate with the mysql database.Make sure XAMPP/WAMP is on..
DeleteOr 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
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.
DeleteMr SAGAR J , i need your help. liza_5757@yahoo.com
DeleteYes?Pls mail me directly or rply to this post..
Deletewhat help u want.
DeleteI 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.
ReplyDeleteHOW TO CLEAR LAST APPENDED DATA FROM FORM.
Now I have solved this problem by using deleteAll() method
DeleteCan you give me good approach to retrieve bulk amount of data from database???
Deleteany possible to add swing class to j2me or anyway is available to design a form in j2me
ReplyDeleteWell 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.
DeleteI have run the program and its working. How to get the values from database and display it on to the mobile screen??
ReplyDeletevenkat please display your working code here
ReplyDeletei 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.....
ReplyDeletejust tried it with php..works smoothly..and more reliable...
ReplyDeleteheres a sample code
http://thinkdiff.net/j2me/communication-between-j2me-client-and-php-page-in-server/
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 :)
DeleteI have run the program and its working. How to get the values from database and display it on to the mobile screen?
ReplyDeleteEmail ID: mr.vipintyagi@gmail.com
baarrrr
ReplyDeleteguys 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...
ReplyDeletei have copied this code and whenever i do login it showing me 0 why???
ReplyDeleteplease someone help me.
Thanks
android.amitsuri@gmail.com
This comment has been removed by the author.
DeleteI have done the required changes and now my application is working fine......
ReplyDeletehow do you create, execute the servlet.. i need the step by step guideline... i use netbeans 6.9
DeleteHow to create a servlet
ReplyDeletehello, 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
ReplyDeleteDo 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.
ReplyDeleteplease don't post such a thing if u too don't understand it very well.
Hey guys i got the right solution for the above problem thanks for your help
ReplyDelete