kendo ui grid is not receiving json data from servlet - java

i have a netbeans web application named javaservlet.this project package has one servlet databaseconnection.java.here i have retrieved 6 rows from a database table employee which has 3 columns eid,ename,esalary and show it as json value
in "http://localhost:8084/javaservlet/databaseconnection" url.Now i want to show all 6 rows of data in kendo grid.In index.html page which is in WEB-INF folder i have tried to read json data from url.but it is not working.i have added three titles EmployeeSalary,EmployeeName,EmployeeId in kendo ui grid and three string fields.when i run the file only showing thevalue when database table has only one row but when table has more than one row kendo is not showing any data ..why is this happening.kindly help me to solve the problem.here is my code
databaseconnection.java
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.*;
#WebServlet(urlPatterns = {"/databaseconnection"})
public class databaseconnection extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
Connection connection = null;
Statement stmt = null;
JSONArray jArray = new JSONArray();
JSONObject jobj = new JSONObject();
try {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test", "postgres", "root");
stmt = connection.createStatement();
// String sql = "INSERT INTO employee (eid,ename,esalary) " + "VALUES (7, 'Nadia', 35000)";
// stmt.executeUpdate(sql);
ResultSet result = stmt.executeQuery("Select eid,ename,esalary from employee");
while (result.next()) {
String eid = result.getString("eid");
String ename = result.getString("ename");
String esalary = result.getString("esalary");
jobj.put("eid", eid);
jobj.put("ename", ename);
jobj.put("esalary", esalary);
out.print(jobj);
out.flush();
// jArray.put(jobj);
// System.out.print(jobj);
}
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
} catch (ClassNotFoundException ex) {
Logger.getLogger(databaseconnection.class.getName()).log(Level.SEVERE, null, ex);
}
}

Pls add the jsonobject into jsonarray inside the while loop.ex:
while (result.next()) {
String type_json = result.getString("eid");
String name_json = result.getString("ename");
String id_json = result.getString("esalary");
jobj.put("eid", type_json);
jobj.put("ename", name_json);
jobj.put("esalary", id_json);
**jArray.add(jobj);**
}

Sara5, I think you should declare array object of Json class like below
JSONArray allArray = new JSONArray();
then
while (result.next()) {
String type_json = result.getString("eid");
String name_json = result.getString("ename");
String id_json = result.getString("esalary");
jobj.put("eid", type_json);
jobj.put("ename", name_json);
jobj.put("esalary", id_json);
allArray.add(jobj);
}
then after this , we create a default JSON object to contain all array and number of JSON objects as below
JSONObject myObj = new JSONObject();
myObj.put("success", true);
myObj.put("data", allArray); // all JSON objects
myObj.put("total", total);// total number of JSON objects
response.setContentType("application/json");// don't forget this
PrintWriter writer = response.getWriter();
writer.println(myObj.toString());

Pls try to use the below libs
json-lib-2.2.2-jdk15
commons-lang 2.5
commons-beanutils 1.8.0
commons-collections 3.2.1
commons-logging 1.1.1
ezmorph 1.0.6
change your code like this..
response.setContentType("application/json");
while (result.next()) {
String type_json = result.getString("eid");
String name_json = result.getString("ename");
String id_json = result.getString("esalary");
jobj.put("eid", type_json);
jobj.put("ename", name_json);
jobj.put("esalary", id_json);
**jArray.add(jobj);**
}
String output = jArray.toString();
PrintWriter writer = response.getWriter();
writer.write(output);`enter code here`
writer.close();
return "success";
The above code snippet will write the json output to the respective jsp whose forward is "success".

Related

How do I use createQuery() Method to create JDBC Connection, using sql2o?

The createQuery() method is wanting a cast to a Connection object, but seems that this method would work on a SQL2o object since it is in the package....
I am using sql2o to create my database connection; however, I do not understand why the use of .createQuery() method is wanting to be cast to a Connection object?
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.sql2o.Sql2o;
import com.google.gson.Gson;
import com.models.Person;
import com.tools.DBUtil;
import com.tools.DataTable;
/**
* Servlet implementation class SalesTeam
*/
#WebServlet(name = "SalesTeam_Table", urlPatterns = { "/json/table/salesteam" })
public class Table_SalesTeam extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Table_SalesTeam() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Creating an arraylist based on the Person model in com.models
ArrayList<Person> people = new ArrayList<Person>();
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String DB_URL = "jdbc:mysql://localhost:3306/salesteam";
String USER = "root";
String PASS = "1234 ";
Sql2o sql2o = new Sql2o(DB_URL, USER, PASS);
String sql =
"SELECT empID, fName " +
"FROM salesteam " +
"WHERE empID = 1";
//issue is here...
try (Connection con = sql2o.open()){
people = con.createQuery(sql).executeAndFetch(Person.class);
////////////////////////
//Selecting every record in sales_team table
//pst = conn.prepareStatement("select f_Name, l_Name, email, contactNum from sales_team ORDER BY f_Name ASC ");
//rs = pst.executeQuery();
while (rs.next()) {
//Create a person object and fill fields
Person p = new Person();
p.setfName(rs.getString("f_Name"));
p.setlName(rs.getString("l_Name"));
p.setEmail(rs.getString("email"));
p.setContact(rs.getString("contactNum"));
//Add person to people array list
people.add(p);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
//Must close the database objects
DBUtil.close(conn, pst, rs);
}
//Gson Library was added to WEB-INF/lib
//Creating a new gson object to hold json
Gson gson = new Gson();
//Create a custom DataTable object that takes an ArrayList<Object> and makes an object
//Used to create correct datatable json formatting
DataTable table = new DataTable();
table.setData(people);
//Creating string by converting people arraylist to json string with gson object
//Read up on gson library for json at http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
String json = gson.toJson(table);
//Uncomment line below and look in console for what json looks like
System.out.println(json);
//Write json string to response
PrintWriter out = response.getWriter();
out.print(json);
out.flush();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Read the Javadoc carefully. sql2o#open() returns an org.sql2o.Connection, which does not inherit from java.sql.Connection. If you want the underlying JDBC Connection object you have to call org.sql2o.Connection#getJdbcConnection()
It appears sql2o is behind the times, as the more recent JDBC API includes methods (Wrapper#unwrap() and isWrapperFor()) to simplify the usage of custom implementations of JDBC classes.
Your code is a mix of plain jdbc and sql2o code. When using sql2o, you should not read manually from the ResultSet. In fact you code would throw a NullPointerException, when trying to read from the ResultSet.
The reason it doesn't compile, is because you have imported java.sql.Connection, and Sql2o.open() method returns a org.sql2o.Connection. I think it would be easier for you, if you just remove every reference JDBC classes.
Your method should look something like this (remember to remove all imports of JDBC classes):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String DB_URL = "jdbc:mysql://localhost:3306/salesteam";
String USER = "root";
String PASS = "1234 ";
Sql2o sql2o = new Sql2o(DB_URL, USER, PASS);
String sql =
"SELECT empID, fName " +
"FROM salesteam " +
"WHERE empID = 1";
List<Person> people;
try (Connection con = sql2o.open()){
people = con.createQuery(sql).executeAndFetch(Person.class);
}
// code to generate json here...
}

Column count doesn't match value count at row.How to match the value

i am working with inserting data into mysql database using jsp why it was not entering into database.the error is showing that "Column count doesn't match value count at row 1"
can anyone solve my problem and say where I've gone wrong please help me frnds
java code
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Dealer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
int a1=0;
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String dealId=request.getParameter("dealer_id");
System.out.println(dealId);
String dealName=request.getParameter("dealer_name");
System.out.println(dealName);
String doorNo=request.getParameter("door_no");
System.out.println(doorNo);
String street=request.getParameter("street");
System.out.println(street);
String city=request.getParameter("city");
System.out.println(city);
String district=request.getParameter("district");
System.out.println(district);
String state=request.getParameter("state");
System.out.println(state);
String pinCode=request.getParameter("pin_code");
System.out.println(pinCode);
String mob=request.getParameter("mobile");
System.out.println(mob);
String contactPerson=request.getParameter("contact_person");
System.out.println(contactPerson);
String phoneNo=request.getParameter("phone_no");
System.out.println(phoneNo);
String emailId=request.getParameter("email_id");
System.out.println(emailId);
String fax=request.getParameter("fax");
System.out.println(fax);
String crdOffI=request.getParameter("credit_offered_i");
System.out.println(crdOffI);
String crdOff=request.getParameter("credit_offered");
System.out.println(crdOff);
String vendorRating=request.getParameter("vendor_rating");
System.out.println(vendorRating);
String gstNo=request.getParameter("gst_no");
System.out.println(gstNo);
String cstNo=request.getParameter("cst_no");
System.out.println(cstNo);
String remarks=request.getParameter("remarks");
System.out.println(remarks);
String saveOrUpdate = request.getParameter("hiddenValue");
System.out.println(saveOrUpdate);
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/charms?user=root&password=root");
System.out.println("Connection created");
PreparedStatement ps =null;
if(saveOrUpdate.equals("update"))
{
ps= ((java.sql.Connection) con).prepareStatement("update dealer_masters set deal_name_v =?, deal_door_no_v =?, deal_street_v =?, deal_city_v =?, deal_district_v=?, deal_state_v=?, deal_contactperson_v=?, deal_phone_no_v=?, deal_mobile_no_v=?, deal_faxno_v=?, deal_email_id_v=?, deal_creditoffered_i=?, deal_period_v=?, deal_vendor_rating_v=?, deal_CST_No_v=?, deal_GST_No_V=?,Remarks_v =? where deal_id_v=? ");
ps.setString(1,dealName);
ps.setString(2,doorNo);
ps.setString(3,street);
ps.setString(4,city);
ps.setString(5,district);
ps.setString(6,state);
ps.setString(7,pinCode);
ps.setString(8,contactPerson);
ps.setString(9,phoneNo);
ps.setString(10,mob);
ps.setString(11,fax);
ps.setString(12,emailId);
ps.setString(13,crdOffI);
ps.setString(14,crdOff);
ps.setString(15,vendorRating);
ps.setString(16,cstNo);
ps.setString(17,gstNo);
ps.setString(18,remarks);
ps.setString(19,dealId);
a1=ps.executeUpdate();
if(a1==1)
{
System.out.println("Inserted");
request.getSession().setAttribute("status1", "updatesuccess");
}
}
else
{
ps= ((java.sql.Connection) con).prepareStatement("insert into dealer_masters(deal_id_v,deal_name_v, deal_door_no_v, deal_street_v, deal_city_v, deal_district, deal_state_v, deal_contactperson_v, deal_phone_no_v, deal_mobile_no_v, deal_faxno_v, deal_email_id_v, deal_creditoffered_i, deal_period_v, deal_vendor_rating_v, deal_CST_No_v, deal_GST_No_V,Remarks_v) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1,dealId);
ps.setString(2,dealName);
ps.setString(3,doorNo);
ps.setString(4,street);
ps.setString(5,city);
ps.setString(6,district);
ps.setString(7,state);
ps.setString(8,pinCode);
ps.setString(9,contactPerson);
ps.setString(10,phoneNo);
ps.setString(11,mob);
ps.setString(12,fax);
ps.setString(13,emailId);
ps.setString(14,crdOffI);
ps.setString(15,crdOff);
ps.setString(16,vendorRating);
ps.setString(17,cstNo);
ps.setString(18,gstNo);
ps.setString(19,remarks);
a1=ps.executeUpdate();
System.out.println("Inserted");
request.getSession().setAttribute("status1", "success");
}
}
catch(Exception e1)
{
System.out.println(e1.getMessage());
request.getSession().setAttribute("status1", "fail");
}
response.sendRedirect("dealer.jsp");
}
}
In this statement:
insert into dealer_masters(
deal_id_v,
deal_name_v,
deal_door_no_v,
deal_street_v,
deal_city_v,
deal_district,
deal_state_v,
deal_contactperson_v,
deal_phone_no_v,
deal_mobile_no_v,
deal_faxno_v,
deal_email_id_v,
deal_creditoffered_i,
deal_period_v,
deal_vendor_rating_v,
deal_CST_No_v,
deal_GST_No_V,
Remarks_v) /* 18 columns */
values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) /* 19 parameters*/
The column list contains 18 columns but the values list contains 19 parameters. I assume you added an extra parameter or missed a column. The SQL statement must be change so the list of columns and parameters is of equals size.
There are 18 bind parameters used in your query but you are setting 19 it seams another deal_creditoffered is missing

How do I read the attachment content on a Defect

Using the Rally Java Rest API, after I get the AttachmentContent object, how do I actually get the bytes which hold the content?
You may find the following example to be useful for what you are wanting to do. It's for a User Story rather than a Defect but the process would be identical for a Defect.
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.DeleteRequest;
import com.rallydev.rest.request.GetRequest;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.DeleteResponse;
import com.rallydev.rest.response.GetResponse;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import com.rallydev.rest.util.Ref;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.commons.codec.binary.Base64;
public class RestExample_DownloadAttachment {
public static void main(String[] args) throws URISyntaxException, IOException {
// Create and configure a new instance of RallyRestApi
// Connection parameters
String rallyURL = "https://rally1.rallydev.com";
String wsapiVersion = "1.43";
String applicationName = "RestExample_DownloadAttachment";
// Credentials
String userName = "user#company.com";
String userPassword = "topsecret";
RallyRestApi restApi = new RallyRestApi(
new URI(rallyURL),
userName,
userPassword
);
restApi.setWsapiVersion(wsapiVersion);
restApi.setApplicationName(applicationName);
// Workspace and Project Settings
String myWorkspace = "My Workspace";
String myProject = "My Project";
// FormattedID of Existing Test Case to Query
String existStoryFormattedID = "US43";
// Get reference to Workspace of interest
QueryRequest workspaceRequest = new QueryRequest("Workspace");
workspaceRequest.setFetch(new Fetch("Name", "Owner", "Projects"));
workspaceRequest.setQueryFilter(new QueryFilter("Name", "=", myWorkspace));
QueryResponse workspaceQueryResponse = restApi.query(workspaceRequest);
String workspaceRef = workspaceQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
// Get reference to Project of interest
QueryRequest projectRequest = new QueryRequest("Project");
projectRequest.setFetch(new Fetch("Name", "Owner", "Projects"));
projectRequest.setQueryFilter(new QueryFilter("Name", "=", myProject));
QueryResponse projectQueryResponse = restApi.query(projectRequest);
String projectRef = projectQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
// Query for existing User Story
System.out.println("Querying for User Story: " + existStoryFormattedID);
QueryRequest existUserStoryRequest = new QueryRequest("HierarchicalRequirement");
existUserStoryRequest.setFetch(new Fetch("FormattedID","Name","Attachments"));
existUserStoryRequest.setQueryFilter(new QueryFilter("FormattedID", "=", existStoryFormattedID));
QueryResponse userStoryQueryResponse = restApi.query(existUserStoryRequest);
JsonObject existUserStoryJsonObject = userStoryQueryResponse.getResults().get(0).getAsJsonObject();
String existUserStoryRef = userStoryQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
JsonArray attachmentsJsonArray = existUserStoryJsonObject.getAsJsonArray("Attachments");
// Take first attachment
JsonObject attachmentObject = attachmentsJsonArray.get(0).getAsJsonObject();
String attachmentRef = attachmentObject.get("_ref").toString();
// Read attachment from Ref
System.out.println("Reading First Attachment: " + attachmentRef);
GetRequest attachmentRequest = new GetRequest(attachmentRef);
attachmentRequest.setFetch(new Fetch("Name","Content"));
GetResponse attachmentResponse = restApi.get(attachmentRequest);
// AttachmentContent object
JsonObject attachmentContentObject = attachmentResponse.getObject().get("Content").getAsJsonObject();
String attachmentContentRef = attachmentContentObject.get("_ref").toString();
// Read Content from Ref
System.out.println("Reading Attachment Content: " + attachmentRef);
GetRequest contentRequest = new GetRequest(attachmentContentRef);
contentRequest.setFetch(new Fetch("Content"));
GetResponse contentResponse = restApi.get(contentRequest);
// Read Content String of AttachmentContent
String attachmentContentBase64String = contentResponse.getObject().get("Content").getAsString();
// Grab attachment name
String attachmentName = attachmentResponse.getObject().get("Name").getAsString();
// Decode base64 string into bytes
byte[] imageBytes = Base64.decodeBase64(attachmentContentBase64String);
// Image output
String imageFilePath = "/Users/username/Desktop/";
String fullImageFile = imageFilePath + attachmentName;
// Write output file
System.out.println("Writing attachment to file: " + attachmentName);
try {
OutputStream imageOutputStream = new FileOutputStream(fullImageFile);
imageOutputStream.write(imageBytes);
imageOutputStream.flush();
imageOutputStream.close();
} catch (Exception e) {
System.out.println("Exception occurred while write image file ");
e.printStackTrace();
}
finally {
//Release all resources
restApi.close();
}
}
}

how to call a java class method in javascript using ajax ?

i have a java class ::
package MyPackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.google.gson.Gson;
public class PopulateTextbox {
Gson gson = new Gson();
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
String temp1;
String temp;
List <String>rowValues = new ArrayList<String>();
List <Integer>rowValues1 = new ArrayList<Integer>();
String[] contactListNames;
Connection con=null;
Statement st=null;
ResultSet rs=null;
public String method(){
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:Practice_Database";
con = DriverManager.getConnection(db,"","");
st = con.createStatement();
String sql = "SELECT Emp_Name,ID,Email_Add FROM EmployeeSearch";
rs = st.executeQuery(sql);
while(rs.next()){
obj.put("ID", rs.getInt("ID"));
obj.put("Names",rs.getString("Emp_Name"));
obj.put("Email", rs.getString("Email_Add"));
arr.add(obj);
}
//obj.accumulate("ID",rowValues1);
//obj.accumulate("Names",rowValues);
temp1 = arr.toString();
System.out.println(temp1);
}catch(Exception e){System.out.println(e);}
/*finally{
try {
if(con!=null)con.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(rs!=null)rs.close();
} catch (SQLException e) {
e.printStackTrace();
}try {
if(st!=null)st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}*/
return temp1;
}
public static void main(String args[])
{
PopulateTextbox obj = new PopulateTextbox();
String temp1= obj.method();
}
}
This is returning me a Json array. Now i want to call method() of this class in JavaScript again and again to get new values as i update my database. I have a data grid which is working fine as the page loads for the first time with a set of values in this json array. But how to refresh data using Ajax. Or how to call the method() using Ajax so that data gets refreshed when i click on a button on the page. The code where i am calling this method in java-script is ::
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
i am getting problem in retrieving new set of values in temp1 through a Ajax call to the server . please help ? Thanks.
Create a blank JSP (for example, textBoxAjaxResp.jsp) and out put your JSON string from that JSP:
<%
String temp1;
PopulateTextbox obj = new PopulateTextbox();
temp1 = obj.method();
%>
<%=temp1 %>
and hit that JSP using jQuery AJAX call.
$.get("mypath/textBoxAjaxResp.jsp", function (response) {
//do operation using the response
}, "json");
you can use Direct Web Remoting library to call java functions using javascript
But I would suggest to write servlet (tutorial is pretty old but good, you should use servlet 3.0 if possible) yourself (instead of using DWR which will have their servlet to write to the response stream also this is very simple requirement so you should write servlet yourself instead of using third party library) and write JSON response directly.
You might want to look at my answer here Updating contents of a jsp page without refreshing this uses a SpringMVC class which returns a text value from server side to client side using jquery ajax.

Respond to a get request in java using a database

I'm trying to respond to a get request in java using a database. But it throws some error which I don't know a clue how to fix it.
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException{
try{
//Accessing driver from the JAR file
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
//Connect to Clockie's database
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/database", "root", "root");
//Here we create our query
String sql = "" +
"SELECT * " +
"FROM profiles " +
"WHERE profileId = '27'";
PreparedStatement statement = con.prepareStatement(sql);
ResultSet result = statement.executeQuery();
String xmls = "";
result.next();
xmls = result.getString("firstName") + " "+result.getString("lastName");
System.out.println(xmls);
resp.getWriter().println(xmls);
}
catch(Exception e){
System.err.println(e.getMessage());
}
}
}
Everything is fine though, if I set the doGet code block inside the a main method? I'm new to Java pls help!
EDIT:
the exception is "com.mysql.jdbc.Driver";
Print out the full stack trace using e.printStackTrace(); in your catch block.
You may not have the mysql-connector jar which contains com.mysql.jdbc.Driver on your classpath. Check your classpath by printing it out using:
System.out.println("classpath = " + System.getProperty("java.class.path"));

Categories