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...
}
Related
Am trying to retrieve records from a database.Connection to database is verified on eclipse, but no information is updated on the jsp table. Am using a servlet class for dispatching, a java class for database replication (model) and jsp (view) that displays the table.
Here is MyUtils.DbAcess class containing the "forRecipient" method`
package myPackage.Utils;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import java.sql.Connection;
import myPackage.beans.MatchTable;
import myPackage.beans.PhedUser;
import myPackage.beans.UserAccount;
public class DbAcess {
.
.
.
public static MatchTable forRecipient(Connection conn, String
recipient) throws SQLException {
String query = "SELECT payer, payerPhone, payerEmail FROM
match_table WHERE recipientAccName=?;";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, recipient);
ResultSet rs = ps.executeQuery();
List <MatchTable> list = new ArrayList<MatchTable>();
while(rs.next()) {
String payer = rs.getString("payer");
String payerPhone = rs.getString("payerPhone");
String payerEmail = rs.getString("payerEmail");
MatchTable payerDetails = new MatchTable();
payerDetails.setPayer(payer);
payerDetails.setPayerPhone(payerPhone);
payerDetails.setPayerEmail(payerEmail);
list.add(payerDetails);
}
return list;
}
This is my database model which is the MatchTable.java
package myPackage.beans;
import java.io.Serializable;
public class MatchTable implements Serializable {
private String payer, payerPhone, payerEmail, recipientAccName,
recipientBankName, recipientAccNumber, recipientPhone;
public MatchTable() {
// TODO Auto-generated constructor stub
}
public MatchTable(String payer, String payerPhone, String payerEmail) {
this.payer = payer;
this.payerPhone = payerPhone;
this.payerEmail = payerEmail;
}
public MatchTable(String recipientAccName, String recipientBankName, String recipientAccNumber, String recipientPhone) {
this.recipientAccName = recipientAccName;
this.recipientBankName = recipientBankName;
this.recipientAccNumber = recipientAccNumber;
this.recipientPhone = recipientPhone;
}
public String getPayer() {
return payer;
}
public void setPayer (String payer) {
this.payer = payer;
}
public String getPayerPhone() {
return payerPhone;
}
public void setPayerPhone(String payerPhone) {
this.payerPhone = payerPhone;
}
public String getPayerEmail() {
return payerEmail;
}
public void setPayerEmail(String payerEmail) {
this.payerEmail = payerEmail;
}
public String getRecipientAccName() {
return recipientAccName;
}
public void setRecipientAccName(String recipientAccName) {
this.recipientAccName = recipientAccName;
}
public String getRecipientBankName() {
return recipientBankName;
}
public void setRecipientBankName(String recipientBankName) {
this.recipientBankName = recipientBankName;
}
public String getRecipientAccNumber() {
return recipientAccNumber;
}
public void setRecipientAccNumber(String recipientAccNumber) {
this.recipientAccNumber = recipientAccNumber;
}
public String getRecipientPhone() {
return recipientPhone;
}
public void setRecipientPhone(String recipientPhone) {
this.recipientPhone = recipientPhone;
}
}
Then I call the "DbAcess.forRecipient" method in my Servlet class and request dispatch to view jsp file "ghTransactions" below;
package myPackage.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import myPackage.Utils.DbAcess;
import myPackage.Utils.SessionAccess;
import myPackage.beans.MatchTable;
import myPackage.beans.UserAccount;
/**
* Servlet implementation class GHTransaction
*/
#WebServlet(urlPatterns={"/ghTransactions"})
public class GHTransactionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GHTransactionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
HttpSession session = request.getSession();
Connection conn = SessionAccess.getStoredConnection(request);
//Get stored match details
//MatchTable payerDetails = SessionAccess.getStoredMatchTable(session);
String errorString = null;
String payer = null;
String payerPhone = null;
String payerEmail = null;
MatchTable Payer = new MatchTable(payer, payerPhone, payerEmail);
//Get loggedInUser Details to retrieve user account name for query to match table database
UserAccount loggedInUser = SessionAccess.getStoredLoggedInUser(session);
String recipientAccName = loggedInUser.getAccountName();
try{
DbAcess.forRecipient(conn, recipientAccName);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
request.setAttribute("user", loggedInUser.getUserName());
request.setAttribute("payer", Payer);
RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/ghTransactionView.jsp");
dispatcher.forward(request, response);
}
/**
* #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);
}
}
My stackTrace snapshot shows successful connection to the database
Sat Apr 29 18:54:11 WAT 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
However the view is not populated with the records even when there are matching details.
Below is the ghTransactionView.jsp file
<section id="about">
<div class="container">
<div class="row">
<center>
<h3>Payer Details</h3>
<table style="width:100%; padding:6px;" border="1" cellpadding="3" cellspacing="3">
<tr>
<th> Name</th>
<th> Phone</th>
<th> Email</th>
</tr>
<c:forEach items="${payer }" var="payerDetails">
<tr>
<td>${payerDetails.payer }</td>
<td>${payerDetails.payerPhone }</td>
<td>${payerDetails.payerEmail }</td>
</tr>
</table>
</center>
</div>
</div>
</section>
I need assistance as to where I have gone wrong and why the records are not populated.
Thank you.
You did not collect and pass the queried list to the JSP i.e., the data returned from forRecipient has not been used.
So you need to add the below code in your GHTransactionServlet doGet() method:
//Collect the returned list using a ref. variable
List<MatchTable> matchTableList =DbAcess.forRecipient(conn, recipientAccName);
//Now set the data to request scope so that JSP can access it
request.setAttribute("payer", matchTableList);
Also, the important point is that the request scope matchTableList object has been set with key as payer which is the same as the items attribute for the tag c:forEach inside JSP.
Here is my current servlet code. This is where I will get the image from the database.
newServlet.java
package LAWS_SERVLETS;
import LAWS_DAOS.LReceiptsDAO;
import LAWS_ENTITIES.Lawyer_Receipt;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author Meryl
*/
#WebServlet(name = "newServlet", urlPatterns = {"/newServlet"})
public class newServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
LReceiptsDAO lrDAO = new LReceiptsDAO();
int imageId = Integer.parseInt(request.getParameter("id"));
// Check if ID is supplied to the request.
if (imageId == 0) {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
byte[] image = lrDAO.getReceiptFile(imageId);
// Check if image is actually retrieved from database.
if (image == null) {
// Do your thing if the image does not exist in database.
// Throw an exception, or send 404, or show default/warning image, or just ignore it.
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
return;
}
// Init servlet response.
response.reset();
response.setContentType(image.getContentType());
response.setContentLength(image.getContent().length);
// Write image content to response.
response.getOutputStream().write(image.getContent());
}
}
LReceiptsDAO
public byte[] getReceiptFile(int id){
byte[] l = null;
try {
DBConnectionFactory myFactory = DBConnectionFactory.getInstance();
Connection conn = myFactory.getConnection();
PreparedStatement pstmt = conn.prepareStatement("SELECT receipt_filepath FROM lawyer_receipts"
+ "where lawyerreceipt_id = ? ");
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
l = rs.getBytes("receipt_filepath");
}
conn.close();
return l;
} catch (SQLException ex) {
Logger.getLogger(LReceiptsDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I got the servlet code from this link but it seems that I get an error when I set the init servlet response part.
I'm very sorry for asking this question. It's my first time trying to get image blobs from the database and getting it via a DAO and a servlet and so far, I only saw codes that included the java codes in a jsp.
I appreciate the help. Thank you!
try replace
response.setContentType(image.getContentType());
response.setContentLength(image.getContent().length);
response.getOutputStream().write(image.getContent());
to
response.setContentType("image/*");
response.setContentLength(image.length);
response.getOutputStream().write(image);
The reason the getContentType() and getContent() methods aren't found is because they don't exist. The type of the variable image is byte[] - an array of primitive bytes - and arrays don't have those methods. That code shouldn't actually compile.
The link where you got that code has the type of image variable as com.example.model.Image (a class which has been defined in that example and has those methods) not byte[].
Incidentally, the code in your example is selecting a field called receipt_filepath which suggests that the field stores the path to the image on disk, not a blob. If so, you should resolve that path and read the file from disk (as is done in the example you linked to).
If it is a blob, then you really should be storing the content type of the image in the database, too. In that case, you can do something like this:
PreparedStatement pstmt = conn.prepareStatement("SELECT image_blob_field_name, image_content_type_field_name FROM lawyer_receipts"
+ "where lawyerreceipt_id = ? ");
...
byte[] image = rs.getBytes(1);
String contentType = rs.getString(2);
...
Then later:
response.setContentType(contentType);
response.setContentLength(image.length);
response.getOutputStream().write(image);
I am trying to write a simple web service that must take a number as input and return details corresponding to it.
Here is my code that I have written till now.
package webserviceapp;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.jws.WebService;
import javax.jws.WebMethod;
#WebService
public class WebServiceApp {
/**
* #param args the command line arguments
*/
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://10.100.66.28:3306/dbname";
// Database credentials
static final String USER = "user";
static final String PASS = "pass";
static Map<Integer, String> map = new HashMap<Integer, String>();
public static void main(String[] args) {
// TODO code application logic here
Connection conn;
Statement stmt;
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = (Statement) conn.createStatement();
String sql = "Select * from table";
ResultSet rs;
rs = stmt.executeQuery(sql);
while(rs.next()){
//do something
}
}catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
#WebMethod(action = "returnDetails")
public static String[] returnDetails(int k) throws notFoundException{
//do the work
//returns String[]
}
private static class notFoundException extends Exception {
public notFoundException(String s) {
System.out.println(s);
System.err.println(s);
}
}
}
I do not know how to take input for the above web service. I have a html page that has a text box and submit button for which I get values through a php code. I want to tunnel this number as input to my web service. Can anyone tell me how can I proceed.
Also, I want the output String[] to be returned to php code so it can be displayed on the html page.
Thanks in advance.
you can pass it in the URL and from the url you can get the values in java
Working off the assumption that you are looking to invoke a RESTful service, there are multiple ways of obtaining input parameters. You can refer to the below article for the ways to achieve this -
http://www.java4s.com/web-services/how-restful-web-services-extract-input-parameters
Code examples for each are available at http://www.java4s.com/web-services/
Another good article you can refer to is - https://vrsbrazil.wordpress.com/2013/08/07/passing-parameters-to-a-restful-web-service/
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".
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