How to fetch data from DataBase using Servlet ?
Hi all,
Till now, i was just sending values from web page and receive the data in excel format using servlets.
But, now, i want to fetch data from data base. I will be giving inputs in the web page(for the query)....ON click of submit button,
Servlet should be called.
Depending on the input, query has to be executed, and response should be sent to the user.
How to do it?
Code
import java.text.*;
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.OutputStream;
/** Simple servlet that reads three parameters from the html
form
public class Fetchdata extends HttpServlet
String query=new String();
String uid="ashvini";
String pwd="******";
try
Connection con=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Testing";
con = DriverManager.getConnection(url, uid, pwd);
Statement s = con.createStatement();
query = "select * from gowri.msllst1";
ResultSet rs = s.executeQuery(query);
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
response.setContentType("application/vnd.ms-excel");
ServletOutputStream out=response.getOutputStream();
out.println("<HTML>" +"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<table>" +" <th>ITEM Code</th>");
while(rs.next())
out.println("<tr><td>" rs.getString(1).trim()"</tr></td>");
}//end of while
out.println("</table></BODY></HTML>");
}//end of doGet method
}catch(Exception e)
System.out.println(e);
It is giving error message as:
C:\Program Files\Apache Tomcat 4.0\webapps\general\srvlt>javac Fetchdata.java
Fetchdata.java:17: illegal start of type
try
^
Fetchdata.java:48: <identifier> expected
^
2 errors
Is this format is correct? am i placing this doGet method at the right place? is my program's logic is correct?
Please help me?
Regards
AShvini
There is some mistakes in ur code.....how can try catch exists outside a function???
make use of try catch isde ur doGet method and put
Connection con=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Testing";
con = DriverManager.getConnection(url, uid, pwd);
Statement s = con.createStatement();
query = "select * from gowri.msllst1";
ResultSet rs = s.executeQuery(query);
isdie doGet method, for the time being,
i think u get me..
regards
shanu
Similar Messages
-
How to fetch data from Database using SUP MBOs
I'm learning to develop blackberry apps using SUP.I am new to both blackberry api and SUP.
I need to make a login page for a Student and then validate the username and password entered using data from a database.
I need to check the database for the username and password entered. What should be my next step? How do i get this data from the database. Using findAll() method is not working . Do i need to connect to SCC or unwired server first. If yes , then someone please provide a sample code for it.Hi!, I see your code and I see that you have a fee errors, try to use this:
import java.text.*;
import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.OutputStream;
* NOTE: You must put the try-catch and your sql code into the get method
/** Servlet program to take fetchdata from database and display that on the broswer*/
public class Fetchdata
extends HttpServlet {
String query = new String();
String uid = "ashvini";
String pwd = "******";
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, Exception {
try {
Connection con = null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Testing";
con = DriverManager.getConnection(url, uid, pwd);
Statement s = con.createStatement();
query = "select * from gowri.msllst1";
ResultSet rs = s.executeQuery(query);
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
out.println("<HTML>" + "<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<table>" + " <th>ITEM Code</th>");
while (rs.next()) {
out.println("<tr><td>" + rs.getString(1).trim() + "</td></tr>");//I change </tr></td> for </td></tr>
} //end of while
out.println("</table></BODY></HTML>");
catch (Exception e) {
System.out.println(e);
} //end of doGet method
}I hope this help you :) -
How to fetch data from database in javafx 2.2 table which is editable.
Dears!
I want to fetch data from database in javafx 2.2 tableformat with jdbc , which is also editable and i can add more records in this table also.
Can anybody help meI can vaguely recall some sort of JavaFX database connectivity feature, I'm not sure if it's valid anymore.The link is based on JavaFX Composer which only applied to NetBeans 6.9 and JavaFX 1.x (both of which are now dead techs).
There is a good chance you will have to write your own. There are several blogs describing other peoples' work. You could probably use them as a reference.Here is Narayan's basic [url http://blog.ngopal.com.np/2011/10/19/dyanmic-tableview-data-from-database/] tutorial for displaying data from a database in a TableView, you'll need to look elsewhere for the editing portion.
The [url http://docs.oracle.com/javafx/2/ui_controls/table-view.htm]JavaFX TableView tutorial gives info about how to handle edits in a TableView, but you will need to tie the updates back to the database yourself.
It is possible that [url http://www.javafxdata.org/]DataFX may provide some facilities to help support you. -
Help , How to get data from database using recordset with UI API
I want to get a data from database
when I want to create recordset i notice that UI API didn't has record set
so I created recordset using DI API (SAPbobscom.recordset and SAPbobscom.company)
======================================================
Dim oCompanyUI As SAPbouiCOM.Company <<UI API
Dim oRecSet As New SAPbobsCOM.Recordset << DI API
Dim oCompanyDI As New SAPbobsCOM.Company << DI API
'=====================================================
oCompanyDI.Connect
Set oRecSet = oCompanyDI.GetBusinessObject(BoRecordset)
oRecSet.DoQuery ("SELECT T0.CardCode, T0.CardName FROM OCRD T0")
SBO_Application.MessageBox oRecSet.Fields.Item(1).Value
======================================================
but I got an error it said "you are not connected to company"
I'm really don't have an idea about how to get a data from using UI API (exp I want to get a date or costumer code)
can someone help me please, I really need it
Thanksyou need a single sign on
Dim oDICompany As SAPbobsCOM.Company
Dim sCookie As String
Dim sConnStr As String
Dim ret As Integer
oDICompany = New SAPbobsCOM.Company
sCookie = oDICompany.GetContextCookie
sConnStr = SBO_Application.Company.GetConnectionContext(sCookie)
If oDICompany.Connected Then
oDICompany.Disconnect()
End If
ret = oDICompany.SetSboLoginContext(sConnStr)
If Not ret = 0 Then
SBO_Application.MessageBox("set Login Context failed!")
Exit Sub
End If
ret = oDICompany.Connect()
If Not ret = 0 Then
SBO_Application.MessageBox("Company Connect failed!")
End If -
How save & retrive data from database using flex, coldfusion, sql server
hi , i am very new in flex, i am trying to insert data in
database using flex2, coldfusion, sql server. any one can help me
please. or give me any example.Hi try to goto the following sites, you will get some
direction to think
http://weblogs.macromedia.com/pent/archives/2006/11/example_of_flex.cfm
http://pdxphp.org/node/258
Good Luck -
Fxml ComboBox created in scene builder how to fetch data from database
Hi Sir, How r u? Hope to be fine. Sir, I have a problem that i want to fetch data in fxml comboBox created in Scene Builder?
I have used this code in JavaFx 2.0 for comboBox and textField the code is
ComboBox studentRegId = new ComboBox();
try{
stm = db.con.createStatement();
rs = stm.executeQuery("select * from students order by s_reg_id asc");
while(rs.next()){
for(int i=1; i<=1; i++)
studentRegId.getItems().add(rs.getString("s_reg_id"));
}catch(SQLException sqlException){
final TextField sRegId = new TextField();
final String regId[] = new String[1000];
try{
stm = db.con.createStatement();
rs = stm.executeQuery("select * from students order by s_reg_id asc");
int a = 0;
while(rs.next()) {
regId[a] = rs.getString("s_reg_id");
a++; }
}catch(SQLException sqlException){
studentRegId.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>(){
public void changed(ObservableValue ov,Number value, Number new_value){
sRegId.setText(regId[new_value.intValue()]);
Now, the problem is that I want to use this code in Scene Builder fxml ComboBox .
Please Help Me!
I shall be very grate full to you for this kindness.
RegardsHi,
Ok, so you create your FXML :
Add a controller property to your root control. (See Code tab in SceneBuilder or direcly in FXML : fx:controller tag)
Add a fx:id to your controls (your combobox) (First property in SceneBuilder or directly in FXML : fx:id)
Example :
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.collections.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<HBox prefHeight="-1.0" prefWidth="-1.0" xmlns:fx="http://javafx.com/fxml" fx:controller="org.lgringo.comboexample.Controler">
<children>
<TextField fx:id="text" prefWidth="100.0" />
<ComboBox fx:id="combo" prefWidth="200.0">
<items>
<FXCollections fx:factory="observableArrayList">
<String fx:value="Item 1" />
<String fx:value="Item 2" />
<String fx:value="Item 3" />
</FXCollections>
</items>
</ComboBox>
</children>
</HBox>Then, you create your Controler class using @FXML annotation (name of control should be the name of fx:id properties)
You can do some initialisation in the inherit method "initialize"
Example :
package org.lgringo.comboexample;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
public class Controler {
@FXML
// fx:id="combo"
private ComboBox<String> combo; // Value injected by FXMLLoader
@FXML
// fx:id="text"
private TextField text; // Value injected by FXMLLoader
@FXML // This method is called by the FXMLLoader when initialization is complete
void initialize() {
assert combo != null : "fx:id=\"combo\" was not injected: check your FXML file 'ComboboxExample.fxml'.";
assert text != null : "fx:id=\"text\" was not injected: check your FXML file 'ComboboxExample.fxml'.";
// Initialize your logic here: all @FXML variables will have been injected
combo.getItems().clear();
combo.getItems().addAll("John Lennon","Mick Jagger","David Bowie");
combo.getItems().add("Others...");
text.setText("List : ");
}Then you use the FXMLLoader class to load your FXML and Controler.
Example :
package org.lgringo.comboexample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class App extends Application {
* @param args
public static void main(String[] args) {
App.launch(args);
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("ComboboxExample.fxml"));
primaryStage.setTitle("Combo Example");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}More info : http://docs.oracle.com/javafx/2/get_started/fxml_tutorial.htm -
Fetch Data from Database using JSP
Dear friends,
I am developing a portal for my College. The theme is to automate student details.
Here i have Screens for Posting, Editing , Viewing.
In Editing: I fetch the data from the backend using select query.
In the address field: I have value as "Big House".
The user keyed with double quotes when he keyed.
During extraction of the data i put the value inside a textbox as
<input type=text name=st1 value="<%=res.getString("street1")%>">
Here,
the value becomes as
<input type=text name=st1 value=""Big House "">
Here, you can notice that Big house i prefixed by double -double quotes.
The value should be Big House but the values is empty.
What i should. ???
Thanks in Advance.
Rengaraj.RTry this:
<%
String addr = res.getString("street1");
//escape the double quotes from the address
addr = addr.replaceAll("[\"]",""");
%>
<input type="text" name="st1" value="<%=addr%>"> -
Swing Applet in JSP: problem with fetching data from database
i am facing a problem while fetching data from database using Swing Applet plugged in a JSP page.
// necessary import statements
public class NewJApplet extends javax.swing.JApplet {
private JLabel jlblNewTitle;
private Vector vec;
public static void main(String[] args) {
JFrame frame = new JFrame();
NewJApplet inst = new NewJApplet();
frame.getContentPane().add(inst);
((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
frame.pack();
frame.setVisible(true);
public NewJApplet() {
super();
initGUI();
private void initGUI() {
try {
this.setSize(542, 701);
this.getContentPane().setLayout(null);
jlblTitle = new JLabel();
this.getContentPane().add(jlblTitle);
jlblTitle.setText("TITLE");
jlblTitle.setBounds(197, 16, 117, 30);
jlblTitle.setFont(new java.awt.Font("Dialog",1,20));
jlblNewTitle = new JLabel();
this.getContentPane().add(jlblNewTitle);
Vector vecTemp = getDBDatum(); // data fetched fm DB r stored here.
jlblNewTitle.setText(vecTemp.get(1).toString());
jlblNewTitle.setBounds(350, 16, 117, 30);
jlblNewTitle.setFont(new java.awt.Font("Dialog",1,20));
} catch (Exception e) {
e.printStackTrace();
}//end of initGUI()
private Vector getDBDatum() {
// fetches datum from oracle database and stores it in a vector
return lvecData;
}//end of getDBDatum()
}//end of class
in index.jsp page i have included the following code for calling this applet:
<jsp:plugin type="applet" code="NewJApplet.class" codebase="applets"
width="600" height="300">
<jsp:fallback>Could not load applet...</jsp:fallback>
</jsp:plugin>
if i view it in using AppletViewer it runs perfectly and display the data in JLabel. (ie, both jlblTitle and jlblNewTitle).(ie, DATA FETCHES FROM db AND DISPLAYS PROPERLY)
BUT IF I CLICK ON INDEX.JSP, ONLY jlblTitle APPEARS. jlblnNewTitle WILL BE BLANK(this label name is supposed to fetch from database)
EVERY THING IS DISPAYING PROPERLY EXCEPT DATA FROM DATABASE!!!
i signed the applet as follows :
grant {
permission java.security.AllPermission;
Can any body help me to figure out the problem?This is the Swing Applet java code
import java.awt.Dimension;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JScrollPane;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
public class HaiApplet extends javax.swing.JApplet {
private JLabel jlblTitle;
private JLabel jlblNewTitle;
private Vector vec;
* main method to display this
* JApplet inside a new JFrame.
public static void main(String[] args) {
JFrame frame = new JFrame();
NewJApplet inst = new NewJApplet();
frame.getContentPane().add(inst);
((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
frame.pack();
frame.setVisible(true);
public HaiApplet() {
super();
initGUI();
private void initGUI() {
try {
this.setSize(542, 701);
this.getContentPane().setLayout(null);
jlblTitle = new JLabel();
this.getContentPane().add(jlblTitle);
jlblTitle.setText("OMMS");
jlblTitle.setBounds(197, 16, 117, 30);
jlblTitle.setFont(new java.awt.Font("Dialog",1,20));
jlblTitle.setHorizontalAlignment(SwingConstants.CENTER);
jlblTitle.setForeground(new java.awt.Color(0,128,192));
jlblNewTitle = new JLabel();
this.getContentPane().add(jlblNewTitle);
Vector vecTemp = getDBDatum();
jlblNewTitle.setText(vecTemp.get(1).toString());
jlblNewTitle.setBounds(350, 16, 117, 30);
jlblNewTitle.setFont(new java.awt.Font("Dialog",1,20));
} catch (Exception e) {
e.printStackTrace();
}//end of initGUI()
private Vector getDBDatum() {
Vector lvecData = new Vector(10,5);
Connection lcon = null;
Statement lstmt = null;
ResultSet lrsResults = null;
String lstrSQL = null;
String lstrOut = null;
try {
OmmsDBConnect db = new OmmsDBConnect();
lcon = db.connectDb();
lstmt = lcon.createStatement(lrsResults.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
lstrSQL = "select DT_ID from P_DATATABLES";
lrsResults = lstmt.executeQuery(lstrSQL);
int i = 0;
lrsResults.last();
int length = lrsResults.getRow();
System.out.println(length);
lrsResults.beforeFirst();
int recCount = 0;
while (lrsResults.next()) {
recCount++;
lvecData.addElement(new String(lrsResults.getString("DT_ID")));
// System.out.println("ID : " + lrsResults.getString(1));
i++;
}System.out.println("here 3 out fm while");
catch(SQLException e) {
System.out.print("SQLException: ");
System.out.println(e.getMessage());
catch(Exception ex) {
lstrOut = "Exception Occured " + ex.getMessage();
finally {
try {
lrsResults.close();
lstmt.close();
lcon.close();
System.out.println("[DONE]");
catch(Exception e) {
System.out.println(e);
}//end of finally
return lvecData;
}//end of getDBDatum()
}//end of classOfcourse the above code compiles and runs well. in Applet Viewer
I plugged the above Swing Applet in a JSP page index.jsp
<jsp:plugin type="applet" code="NewJApplet.class" codebase="applets"
width="600" height="300">
<jsp:fallback>Could not load applet...</jsp:fallback>
</jsp:plugin>Every thing is working fine in AppletViewer...But if i view this in any browser, then only the jlblTitle is displaying. jlblNewTitle is not displaying(this label name is actually fetching from thedatabase)
can any body help me regarding this matter.? Thx in Advance. -
How to fetch data from Mysql with SSL.
I am using jdk1.5 and mysql 5.0.
How to fetch data from Mysql with SSL
I am using url = jdbc:mysql://localhost/database?useSSL=true&requireSSL=true.
It shows error. how to fetchI have created certificate in mysql and checked in mysql.
mysql>\s
SSL: Cipher in use is DHE-RSA-AES256-SHA
but through ssl how to fetch data in java. -
How to display data from Database individually??? Anyone can help ?
HI,
i i had select a row of data from database using ,
/* Query * From Table RESOURCEORDER where po = selected no and project = selected project */
public ResultSet getAllData() throws SQLException
getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM RESOURCEORDER WHERE PROJECT = '" + getSelProject() + "' and PURCHASEORDERNO = '" + getPo() + "'" );
return rs;
After that , how do i display the data individually ?
Eg select data is ('projectA','7891203-1', '10-4-2005','lcd',2000,'121-45217-8','electrical','pending','donwong')
i want to display them individually, like this in a page
Projectname: /* should display the Project A*/
P.O no:
Date:
Order:
Cost:
Acc no:
Type:
status:
Orderedby:
Can anyone help ? cos i'm new to JSP ......Thanks alot!!!!!
Regards,
khimI assume PO being a unique key, will always return 1 row from db.
public String[] getAllData() throws Exception
getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM RESOURCEORDER WHERE PROJECT = '" + getSelProject() + "' and PURCHASEORDERNO = '" + getPo() + "'" );
String [] returnValue = new String[9];
while(rs.next())
returnValue[1] = rs.getString("colname");
returnValue[2] = rs.getString("colname");
///and so on
return returnValue;
}Once you get that you could individually view it by setting a loop to run through the returned array.
Hope it helps -
How to fetch data from PTREQ tables
I need to display data in the customised webdynpro application from PTREQ tables.
Can anyone help me out how to fetch data from these tables.use the standard modules like
PT_ARQ_REQUEST_CHECK
PT_ARQ_REQUEST_EXECUTE
PT_ARQ_REQUEST_PREPARE -
How to fetch data from cluster tables
hi
i need to know how to fetch data from cluster tables please update me if any
i know that we cannot use joins in cluster table we use view etc
but i need detailed inforation on methods for fetching data from cluster tables
regards
NishantHi,
Check the following links
http://fuller.mit.edu/hr/cluster_tables.html
The specified item was not found.
https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/library/uuid/a0f46157-e1c4-2910-27aa-e3f4a9c8df33 -
What is a cube? how we store data in that? how we fetch data from cube?
Hi,
What is a cube? how we store data in that? how we fetch data from cube?
Regards.
venkat>
venkey B wrote:
> Hi,
>
>
> What is a cube? how we store data in that? how we fetch data from cube?
>
>
> Regards.
>
> venkat
Hi Venkat,
I guess you mean an infocube from the SAP BI product. I propose to look at the forum for Business Intelligence to find your answers.
E.g. SAP POS DM writes the sales data in infocubes..... -
Question regarding Polling data from database using DB Adapters in BPEL
Hi,
I have the following question regarding Polling data from database using DB Adapters in BPEL -
If I am selecting data from multiple tables/view to ultimately generate hierarchical xml document, is there a way that I specify polling all of these tables/views. Is polling limited only to one table/view?
Thanks
RaviHi Ravi,
your question seems to have been answered for the question of polling a set of tables with one as the root, and getting back a hierarchical xml representing multiple related tables.
However you can also poll for changes to both the root table and its related tables. Not sure if this was your question or the one already answered. If the former please check out the sample
bpel/samples/tutorials/122.DBAdapter/advanced/polling/PollingForChildUpdates
Thanks
Steve -
How to retrive data from database views or projection views
how to retrive data from database views or projection views
Hi chintam,
1. Very simple
2. Just like normal select statement.
3. Select * from VIEWNAME.
4. (Instead of the tablename, we just have to give the viewname)
regards,
amit m.
Maybe you are looking for
-
I photo album. not uploading
I am trying to purchase and album I created in the Iphoto. During the purchase phase, the assembly is completed but it will not upload. It goes about half way and the freezes up. Does anyone know what I can do? Thank you!
-
How to move wsp files from sharepoint 2007 to 2010 farm
Hi experts, we have a share point 2007 farm ,which we are migrating to share point 2010 using database attach upgrade process.i had run pre upgrade checker command and fixed all the issues. now i would like to move the wsp files that are deployed in
-
I want AIX OPERATING SYSTEM, FROM WHERE CAN I DOWNLOAD FOR LEARNING PURPOSE
I AM PRESENTLY WORKING IN WINDOWS OS, DUE TO GOOD DEMAND IN AIX OPERATING SYSTEM AS BACKGROUND FOR ORACLE. I WANT TO LEARN, AIX BUT I DON'T KNOW FROM WHER CAN I GET THIS OPERATING SYSTEM. IF ANY ONE KNOWS PLS REPLY ME ON [email protected]
-
Unresolved Rule: Even when the rule exists in rule library.
Hi, I have a rule called getSAProles sitting in RuleLibrary. When I try to open the form in BPE I get an error Error rendering form:comwaveset.util.WavesetException: Unresolved rule: RuleLibrary :getSAProles Does any one know why? I have the rule in
-
New to Multi-Master replication
First I have to point out that I am teaching all of this stuff to myself and do, for the most part have full access to a set of servers to mess around with all the time. I have two 10.2.0.3 enterprise servers set up and I want to have MM replication