How to delete row in database in MySQL using JSP? - mysql

This is my function. It gets two parameter id of the product and a name. the function delete with MySQL command a row in a database. I know the that there are missing lines in my code, I'm stuck and I don't know how to finish it. I also know that my SQL line is not correct. I'm not sure if combined the String "name" right.
public static deletePro(int cat, String name) {
DB db = new DB();
String sql = "delete from products where pname=+'name' and catid=" + cat;
ResultSet rs = db.getResultSet(sql);
try {
while (rs.next()) {
Products prod = new Products();
prod.setNamePro(rs.getString(name));
prod.setAmount(rs.getInt(cat));
}
rs.close();
db.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
return
}

String sql = "delete from products where pname=+'name' and catid=" + cat;
This should be:
String sql = "DELETE FROM products WHERE pname='" + name + "' and catid = " + cat;
And the preferred way is to use PreparedStatement, which would alleviate the pain of string manipulation in your query by using placeholders:
String sql = "DELETE FROM products WHERE pname= ? and catid = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, cat);
ps.executeUpdate();
Hope this helps.

Related

"JSP First Connection cause second connection not running when it had ended"

I'm trying to get two data(GenreID & GameID) from two different tables(genre & games) and insert them into another table(games_genre). However, it will close the connection to the database after inserting the GenreID successfully even though i had created another new connection to the database.
I have tried to create connection1 and connection2 to the same database. Connection1 is used to insert GenreID and connection2 is used to insert GameID
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
String gametitle = request.getParameter("gametitle");
String [] checkbox1 = request.getParameterValues("checkbox");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
Connection conn2 = DriverManager.getConnection(connURL);
Statement stmt = conn.createStatement();
if (checkbox1!= null){
for(String s: checkbox1){
String sqlStr2 = "Select * FROM genre WHERE GenreName='" + s + "'";
ResultSet rs = stmt.executeQuery(sqlStr2);
while(rs.next()){
String genreid = rs.getString("GenreID");
String sqlStr3 = "INSERT INTO games_genre(GenreID) VALUES ('" + genreid + "')";
int j = stmt.executeUpdate(sqlStr3);
if (j>0) {
out.println("Adding GenreID Successfully!");}
}
}
}
conn.close();
Statement stmt2 = conn2.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
String gameid = rs2.getString("GameID");
String sqlStr5 = "INSERT INTO games_genre(GameID) VALUES ('" + gameid + "')";
int k = stmt2.executeUpdate(sqlStr5);
if (k>0) {
out.println("Adding GameID Successfully!");
}
}
conn2.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Adding Game Successfully! Adding GenreID Successfully! Error :java.sql.SQLException: Operation not allowed after ResultSet closed
I don't understand that why do you need to create two Connection as you need to access same database . So ,just create multiple Statement to execute multiple query like below :
Statement stmt=null;
Statement stmt2=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String connURL ="jdbc:mysql://localhost/assignment?user=root&password=root&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(connURL);
stmt = conn.createStatement();
if (checkbox1!= null){
....
}
<!--using same conn object -->
stmt2 = conn.createStatement();
String sqlStr4 = "Select * FROM games WHERE GameTitle='" + gametitle +"'";
ResultSet rs2 = stmt2.executeQuery(sqlStr4);
if(rs2.next()){
...
}
<!--finally close connection-->
conn.close();
} catch (Exception e) {
out.println("Error :" + e);
}
Note : Also try using PreparedStatement for preventing from Sql Injection as concatenating values into a query string is unsafe .

JDBC pass parameters to sql query

I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).

Using ? in where clause for prepared statements

I have a method that returns an array list of search results from my database.
Instead of:
Select *
from employee
where first_name like ?
I would rather use:
Select *
from employee
where ? like ?
but I'm not sure if this is even possible? there's no errors when I compile it in eclipse but it keeps giving me blank values in the array. Is there something I'm doing wrong?
This is the method that gives me the blank value it works fine when I have where first_name like ? so I know the logic works.
public static ArrayList<String> AdvanceSearchFirstName(String selected, String searchTerm) {
String selectQuery = "select * from employee_info where ? like ?";
ArrayList<String> searchResults = new ArrayList<>();
try {
stmt = con.createStatement();
PreparedStatement ps = con.prepareStatement(selectQuery);
ps.setString(1, selected);
ps.setString(2, '%'+searchTerm+'%');
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
String studentNumber = rs.getString("employee_number");
String combo = employeeNumber + " " + firstName + " " + lastName;
searchResults.add(combo);
}
} catch (SQLException e) {
e.printStackTrace();
}
return searchResults;
}
I've looked over a lot of posts so I'm pretty sure this hasn't been posted but I apologies if this is a double. I'm new to programming and sql so any help is appreciated.

Netbeans put data from a query into a variable

So I made a query, It's a inner join, the query is fine. But I want to put the data that is selected from the database into variables from an other class.
You see the code
Spel spel = null;
spel.setNaamSpel(spelUniekeNaam);
I didn't do it for all but is this the right way to do it?
public void laadSpel(String spelNaam)
{
String LAAD_SPELERS_SQL = "SELECT spel.naam, spel.aantalTeSpelenRondes, speler.naam, speler.kleur, speler.sector, speler.aantalZilverstukken, spelbord.type, spelbord.ecoWaarde, spelbord.stratWaarde, "
+ "spelbord.xcoord, spelbord.ycoord, spelbord.aantalKamelen, spelbord.kleur" +
"From spel INNER JOIN speler ON spel.naam = speler.Spel_naam" +
"INNER JOIN spelbord ON spel.naam = spelbord.Spel_naam" +
"WHERE spel.naam = '" + spelNaam + "'";
Statement statement;
Connection connection = PersistentieController.getInstance().getConnection();
try
{
statement = connection.createStatement();
ResultSet resultset = statement.executeQuery(LAAD_SPELERS_SQL);
while (resultset.next())
{
String spelUniekeNaam = resultset.getString("spel.naam");
String spelAantalRondes = resultset.getString("spel.aantalTeSpelenRondes");
String spelerNaam = resultset.getString("speler.naam");
String spelerKleur = resultset.getString("speler.kleur");
int spelerSector = resultset.getInt("speler.sector");
int spelerKrediet = resultset.getInt("speler.aantalZilverstukken");
String spelbordType = resultset.getString("spelbord.type");
int spelbordEco = resultset.getInt("spelbord.ecoWaarde");
int spelbordStrat = resultset.getInt("spelbord.stratWaarde");
int spelbordX = resultset.getInt("spelbord.xcoord");
int spelbordY = resultset.getInt("spelbord.ycoord");
int spelbordAantalKamelen = resultset.getInt(("spelbord.aantalKamelen"));
String spelbordKleur = resultset.getString("spelbord.kleur");
Spel spel = null;
spel.setNaamSpel(spelUniekeNaam);
}
statement.close();
} catch (SQLException e)
{
e.printStackTrace();
}
}
No.
Your other class Spel variable will not be present outside the while loop.
The spelUniekeNaam will be overwritten with every new record traversed in the resultset.
Please avoid using String concatenation for SQL queries as I pointed out in your earlier post here. This is just asking for an SQL Injection attack.

SELECT a column from a mySQL table and check validation

I have a mySQL table named userinfo with colums- userId, userName, Password, city, age- userId is Pkey and Autoincremnt
When a user Login on a login.jsp, he submits username and Pasword.
These two parameters of login.jsp are received in UserLogin servlet and then checked in userinfo Table. If matched, he could log in.
I tried SELECT but I get numerous error. What should be the correct way:-
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt = (PreparedStatement) conn
.prepareStatement(sql);
ptmt.executeQuery();
Statement stmt = (Statement) conn.createStatement();
s = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?");
//storing user data in ResultSet
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String refName = rs.getString("UserName");
String refPass = rs.getString("UserPW");
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
by using Statement interface you can not dynamically set the values. use PreparedStatement interface for second query.
import package in you class import javas.sql.*;
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser UserName = ?";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt =conn.prepareStatement(sql);
ptmt.setString(1, user)
ResultSet rs= ptmt.executeQuery();
while (rs.next()) {
String refName = rs.getString(1);//field index of user name
String refPass = rs.getString(2);//field index of password
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
Are you asking for the entire code listing? in your current code you seem to be executing some queries for no reason, then getting a list of all users and iterating through them looking for a match. Try using a query like
sql ="Select UserName, UserPW From SocialNetwork.RegisteredUser where UserName=?"
ResultSet rs = stmt.executeQuery(sql);
then check the password in code
if(rs.next()){
String refPass = rs.getString("UserPW");
if (pw.equals(refPass) )
}