Could not load create coonection in addProduct method - java

package com.Foodmart;
import javax.jws.*;
import java.sql.*;
#WebService(name = "FoodMart", serviceName = "FoodMartService", portName = "FoodMartHtt)
public class FoodmartWS {
ProductDetails prod = new ProductDetails();
#WebMethod(operationName = "check")
public boolean Authenticate(String user, String pass) {
PreparedStatement psmt = null;
Connection c = null;
try {
c = ConnectionDB.getConnection();
String selectSQL = "select * from Employee where Username=? and Password=?";
psmt = c.prepareStatement(selectSQL);
psmt.setString(1, user);
psmt.setString(2, pass);
psmt.executeQuery();
c.close();
return true;
} catch (SQLException e) {
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
In this Method Error in AddProduct
#WebMethod(operationName = "AddProduct")
public ProductDetails ProdcutAdd(int prodid, double qty) {
PreparedStatement preparedStatement = null;
Connection con = null;
try {
System.out.println("try");
//here i am not able to create another one connection
con = ConnectionDB.getConnection();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Food", "root", "manager1");
String selectSQL = "select Product_Id,Product_Name,Product_Price,Product_Qty from Products where Product_Id=?;";
System.out.println("bbefore prepared");
preparedStatement = con.prepareStatement(selectSQL);
preparedStatement.setInt(1, prodid);
System.out.println("before result set");
ResultSet rs = preparedStatement.executeQuery();
System.out.println("query Executed");
rs.next();
prod.setProductId(rs.getInt("Product_Id"));
prod.setProductName(rs.getString("Product_Name"));
prod.setProductPrice(rs.getDouble("Product_Price"));
prod.setProductQty(rs.getInt("Product_Qty"));
System.out.println("obj set");
con.close();
System.out.println("in" + prod);
return prod;
} catch (SQLException e) {
System.out.println(e);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

Why you add this line after you get your connection :
con = ConnectionDB.getConnection();
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Food", "root", "manager1");
So just delete it or comment it.
Note
you missed a ") here in the end, so this can also make a problem :
#WebService(name = "FoodMart", serviceName = "FoodMartService", portName = "FoodMartHtt)
Hope this can help you.

Related

What is the right way to deal with the PreparedStatement in the Java program flow?

There are two methods in which the PreparedStatement is used.
The first method is called in the second method.
First method:
protected List<String> findResultsByMandantId(Long mandantId) {
List<String> resultIds = new ArrayList<>();
ResultSet rs;
String sql = "SELECT result_id FROM results WHERE mandant_id = ?";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.setLong(1, mandantId);
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
resultIds.add(rs.getString(1));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return resultIds;
}
Second method:
protected void findResultLineEntityToDelete(Long mandantId, String title, String context) {
List<String> resultIds = findResultsByMandantId(mandantId);
String [] resultIdsArr = resultIds.toArray(String[]::new);
ResultSet rs;
//String sql = "SELECT * FROM resultline WHERE result_id in (SELECT result_id FROM results WHERE mandant_id =" + mandantId + ")";
String sql = "SELECT * FROM resultline WHERE result_id in (" + String.join(", ", resultIdsArr)+ ")";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
if (rs.getString(3).equals(title) && rs.getString(4).equals(context)) {
System.out.println("Titel: " + rs.getString(3) + " " + "Context: " + rs.getString(4));
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The class in which both methods are located extends the JDBCBaseManager.
JDBCBaseManager:
private final String url = "jdbc:mysql://localhost:3306/database";
private final String userName = "root";
private final String password = "";
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private int batchSize = 0;
public JDBCBaseManager() {
// Dotenv env = Dotenv.configure().directory("./serverless").load();
// url = env.get("DB_PROD_URL");
// userName = env.get("DB_USER");
// password = env.get("DB_PW");
}
public void getConnection() {
try {
if (connection == null) {
connection = DriverManager.getConnection(url, userName, password);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
if (connection == null) {
getConnection();
}
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void startBatch(int batchSize) throws SQLException {
connection.setAutoCommit(false);
setBatchSize(batchSize);
}
public void commit() {
try {
if (connection != null && !connection.isClosed()) {
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
The ResultSet in the second method still contains the results from the first method.
I already tried to close the connection and open it again before the second method is executed, but then I get the errors:
java.sql.SQLException: No operations allowed after statement closed.
java.sql.SQLNonTransientConnectionException: No operations allowed
after connection closed.
Can you tell me how to deal with the statement correctly in this case? Is my BaseManager incorrectly structured?
Here lies the error
public JDBCBaseManager() {
private PreparedStatement preparedStatement = null;
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
......
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
You build the prepare statement only the first time the method getPreparedStatement is called because only the first time the field preparedStatement is null. Every next time you call the method getPreparedStatement you receive the previous preparedStatement from the previous SQL and not the new one.
Remove the check for if (preparedStatement == null) {
You need to build a new preparedStatement every time you want to execute a new SQL.

Access Control: Database (Fortify)

public void removerSolicitacao(Long codigoSolicitacao)
throws IntegrationException {
beginMethod(LOGGER, "removerSolicitacao(codigoSolicitacao)");
String delete = null;
try {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = this.getConnection();
delete = "DELETE FROM DBPROD.SOLTC_DISPZ_ARQ WHERE CSOLTC_DISPZ_ARQ = ? ";
preparedStatement = connection.prepareStatement(delete);
preparedStatement.setLong(1, codigoSolicitacao.longValue());
preparedStatement.executeUpdate();
} catch (SQLException sqle) {
LOGGER.fatal(sqle);
throw new IntegrationException(sqle.getMessage());
} finally {
//closeStatement(preparedStatement); original
if(preparedStatement!=null) {
closeStatement(preparedStatement);
}
closeConnection(connection);
}
} finally {
endMethod(LOGGER, "removerSolicitacao(codigoSolicitacao)");
}
}

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

Inserting issue into the database via java

I have a bit of a problem with inserting some data in the database. The data is being read by an CSV parser and changed to data besides that, I continue to get this error message:
Connected to the PostgreSQL server successfully.
Naam van de garage: P_Erasmusbrug, Longditude: 4.482313155, Latitude: 51.91024645
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
at org.postgresql.core.v3.SimpleParameterList.bind(SimpleParameterList.java:65)
at org.postgresql.core.v3.SimpleParameterList.setStringParameter(SimpleParameterList.java:128)
at org.postgresql.jdbc.PgPreparedStatement.bindString(PgPreparedStatement.java:1023)
at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:374)
at org.postgresql.jdbc.PgPreparedStatement.setString(PgPreparedStatement.java:358)
at Database.ConnectDatabase.parser(ConnectDatabase.java:80)
at Events.CSVReader.main(CSVReader.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Thank you for your service.
Naam van de garage: P_St.Jacobsplaats, Longditude: 4.482054381, Latitude: 51.92410235
Thank you for your service.
Naam van de garage: P_Schouwburgplein, Longditude: 4.473618335, Latitude: 51.92102728
org.postgresql.util.PSQLException: The column index is out of range: 1, number of columns: 0.
Which continues for all the other lines of data. Is there maybe a way to fix this as I don't really understand what the error message includes..
The a, b2, and c2 are variables for the ''name'' , ''londitude'' and ''latitude''.
package Database;
import java.io.*;
import java.sql.*;
import java.util.HashMap;
import java.sql.SQLException;
public class ConnectDatabase {
private final String url = "jdbc:postgresql://localhost/Project3";
private final String user = "postgres";
private final String password = "kaas123";
private Connection conn;
public Connection connect() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the PostgreSQL server successfully.");
} catch (SQLException exception) {
System.out.println(exception.getMessage());
}
this.conn = conn;
return conn;
}
public HashMap getGarages() {
HashMap<String, Double> newHashMap = new HashMap<String, Double>();
try {
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT deelgemeente, COUNT(garagenaam) FROM garages GROUP BY deelgemeente");
while (rs.next()) {
String deelGemeenteNaam = rs.getString("deelgemeente");
double garageNaamCount = rs.getDouble("COUNT");
newHashMap.put(deelGemeenteNaam, garageNaamCount);
}
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return newHashMap;
}
public HashMap getTheftYear(int year) {
HashMap<String, Double> newHashMap = new HashMap<String, Double>();
try {
Statement stmt = conn.createStatement();
ResultSet rs;
rs = stmt.executeQuery("SELECT deelgemeente, percentagediefstal FROM autodiefstal WHERE jaar = " + year);
while (rs.next()) {
String deelGemeenteNaam = rs.getString("deelgemeente");
double deelPercentage = rs.getDouble("percentagediefstal");
newHashMap.put(deelGemeenteNaam, deelPercentage);
}
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return newHashMap;
}
public int parser(String a, float b2, float c2) {
int updated = 0;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DriverManager.getConnection(url, user, password);
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(" + a + "," + b2 + "," + c2 + ")";
stmt = conn.prepareStatement(insertSQL);
stmt.setString(1, a);
stmt.setFloat(2, b2);
stmt.setFloat(3, c2);
System.out.println("Inserted data into the database...");
updated = stmt.executeUpdate();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
conn.close();
} catch (SQLException se) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your service.");
this.conn = conn;
return updated;
}
}
You aren't correctly using the ? placeholders system, replace :
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(" + a + "," + b2 + "," + c2 + ")";
with
String insertSQL = "INSERT INTO testparser(garagenaam, xpos, ypos) VALUES(?,?,?)";

JDBC:MySql connection is not working in Ajax request -Java

I have exactly same function in both Main method and other method JDBC connection is working fine. If I call the other function it throws error java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/wine:
I have included MySql Driver in library [Netbeans];
processRequest method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String process = (String) request.getParameter("process");
String name = (String) request.getParameter("process");
String phone=(String) request.getParameter("phone");
String email = (String) request.getParameter("email");
String pwd = (String) request.getParameter("pwd");
PrintWriter out = response.getWriter();
out.println("Hello");
signup(out,process,name,email,phone,pwd);
}
signup method:
private static int signup(PrintWriter out,String process,String name,String email,String phone,String pwd){
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
out.println("Process Not Found");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role) VALUES(?,?,?,?,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
out.println(e);
e.printStackTrace();
return 0;
}
return 1;
}
Main Method :
public static void main(String[] args) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String process = "signup";
String name = "Test";
String phone="45885";
String email = "Test#gmail.com";
String pwd = "dkjsdh";
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wine", "root", "");
if (process == "signup") {
String query = "INSERT INTO user(name,phone,email,password,role,status) VALUES(?,?,?,?,1,1)";
stmt = con.prepareStatement(query);
stmt.setString(1, name);
stmt.setString(2, phone);
stmt.setString(3, email);
stmt.setString(4, pwd);
stmt.execute();
} else {
System.out.println("Process Not Found");
}
} catch (SQLException e) {
// do something appropriate with the exception, *at least*:
System.out.println(e);
e.printStackTrace();
}
}
There are two options that can be tried:
Class.forName("com.mysql.jdbc.Driver").newInstance() //older bug
and
Class.forName("com.mysql.jdbc.Driver");
In the comment I pasted the older bug solution when I meant to paste the second one.
Either way I am glad that it worked out for you

Categories