Modifying my methods to use PreparedStatement Objects instead of Statement Objects - java

How do I modify this code to take in PreparedStatement Objects (instead of Statement Objects)?
package com.cs330;
import javax.ws.rs.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
#Path("ws2")
public class IngredientServices
#Path("/ingredients")
#GET
#Produces("text/plain")
public String getIngredients() throws SQLException, ClassNotFoundException {
String connectStr="jdbc:mysql://localhost:3306/fooddb";
//database username
String username="root";
//database password
String password="csci330pass";
/* The driver is the Java class used for accessing
* a particular database. You must download this from
* the database vendor.
*/
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
//Creates a connection object for your database
Connection con = DriverManager.getConnection(connectStr, username, password);
/* Creates a statement object to be executed on
* the attached database.
*/
Statement stmt = con.createStatement();
/* Executes a database query and returns the results
* as a ResultSet object.
*/
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient");
/* This snippet shows how to parse a ResultSet object.
* Basically, you loop through the object sort of like
* a linkedlist, and use the getX methods to get data
* from the current row. Each time you call rs.next()
* it advances to the next row returned.
* The result variable is just used to compile all the
* data into one string.
*/
String result = "";
while (rs.next())
{
int theId = rs.getInt("id");
String theName = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId+ " , name: "+theName + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END
#Path("/ingredients/{id}")
#GET
#Produces("text/plain")
public String getIngredientById(#PathParam("id") String theId)
throws SQLException, ClassNotFoundException {
int intId = 0;
try
{
intId = Integer.parseInt(theId);
}
catch (NumberFormatException FAIL)
{
intId = 1;
}//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient
WHERE id=" +intId);
String result = "";
while (rs.next())
{
int theId2 = rs.getInt("id");
String theName2 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId2+ " , name: "+theName2 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
#Path("/ingredients/name")
#GET
#Produces("text/plain")
public String getIngredientByName(#QueryParam("name") String theName)
throws SQLException, ClassNotFoundException
{
//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient WHERE
name='" + theName + "'");
String result = "";
while (rs.next())
{
int theId3 = rs.getInt("id");
String theName3 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId3+ " , name: "+theName3 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
}//END CODE
I know for a fact that it is not as simple as just changing the object variable from Statement to PreparedStatement... That's why I'm asking for some suggestions here. Thank You.

Few steps:
Change the type from Statement to PreparedStatement.
Store your queries in String variables. Any place where you should use a dynamic value (e.g. the places where you concatenate a String) will be parameters for your query, replace these variables by ?.
Create the PreparedStatement by using Connection#prepareStatement rather than using Connection.createStatement.
Set the parameters in your PreparedStatement by using setXxx methods.
Execute the statement by using executeQuery method.
An example is covered in PreparedStatement javadoc.
This is how you can change getIngredientById method by following steps above:
Connection con = DriverManager.getConnection(connectStr, username, password);
//from "SELECT id, name, category FROM ingredient WHERE id=" + intId
//check the usage of ? instead of intId
String sql = "SELECT id, name, category FROM ingredient WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
//setting variable in PreparedStatement
pstmt.setInt(1, intId);
ResultSet rs = pstmt.executeQuery();
String result = "";
while (rs.next()) {
//consume the data...
}
This is how you can change getIngredientByName method by following steps above:
Connection con = DriverManager.getConnection(connectStr, username, password);
//? don't need you to escape it by using ' around
//? is equals to the parameter, this is why using PreparedStatement is more safe
//it will help you to avoid SQL Injection attacks
String sql = "SELECT id, name, category FROM ingredient WHERE name = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, theName);
ResultSet rs = pstmt.executeQuery();
String result = "";
while (rs.next()) {
//consume the data...
}
Do similar for the necessary methods in your project.

Related

How can I pass integer into string for sql query

I have written a program that extracts data from an SQL table:
String url = "jdbc:mysql://localhost/petcare";
String password = "ParkSideRoad161997";
String username = "root";
// Step 2: Making connection using
// Connection type and inbuilt function on
// Connection con = null;
PreparedStatement p = null;
ResultSet rs = null;
// Try block to catch exception/s
try {
Connection con = DriverManager.getConnection(url, username, password);
// SQL command data stored in String datatype
String sql = "select * from inbox";
p = con.prepareStatement(sql);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("inboxId");
int inboxId;
// Condition check
while (rs.next()) {
inboxId = rs.getInt("InboxId");
// System.out.println(inboxId);
}
String sql2 = "select * from message where inboxId = int";//this is where i need help
p = con.prepareStatement(sql2);
rs = p.executeQuery();
// Printing ID, name, email of customers
// of the SQL command above
System.out.println("Inbox:");
}
// Catch block to handle exception
catch (SQLException e) {
// Print exception pop-up on screen
System.out.println(e);
}
Once I get the inboxId, I want to run sql2 and pass inboxId as int. How can I do this. Each user will have a different inboxId so thats why to get the user inbox I want to extract and messages in the message table that are meant for inboxId of the user.
I tried the query string sql and it works now I just need to fix String sql2.
String sql2 = "select * from message where inboxId = " + 1234;
1234 could be a variable. You could also use String.format() to do it as well.
String sql2 = String.format("select * from message where inboxId = %d", 1234);
Try this:
String sql2 = "select * from message where inboxId = ?"; //The ? indicates a variable in the prepared statement.
p = con.prepareStatement(sql2);
p.setInt(1, inboxId);
rs = p.executeQuery();

Netbeans java application - executing query on MySql database

In the project I'm working on I need to execute Searching SQL query i.e the wildcard characters in Java Netbeans.
I'm able to execute simple queries like
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid ="+empid+"");
while(rs.next())
{
String name = rs.getString("name");
String salary = rs.getString("salary");
name1.setText(name);
salary1.setText(salary);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
This works completely fine. But now I want to use this MySql query
Mysql>select * from employes where empid like "123%";
instead of this
Mysql>select * from employes where empid =123;
in java Netbeans.
I've tried to do this
String driver = "jdbc:mysql://localhost/techo";
String un = "root";
String pw = "root";
String empid = id.getText();
try{
Connection con = DriverManager.getConnection(driver,un,pw);
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid%+"");
while(rs.next())
{
String id = rs.getString("EmpId");
String name = rs.getString("name");
String salary = rs.getString("salary");
area.setText(id +" "+name+" "+salary+" "+ "\n");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
As you can see that in the 8th line I've inserted the wildcard character(%) but this ain't working. How can I solve this?
Your wildcard character is misplaced.
It should be:
ResultSet rs = stm.executeQuery("select*from employees where empid like "+empid+"%");
In this case the % char will be treated as a wildcard.
If you want to search the % char itself, you have to escape it following the mysql escape rules:
ResultSet rs = stm.executeQuery("select*from employees where empid like \""+empid+"%%\"");
Pay special attention to the quotes

Java Servlet to handle html post data

I am trying to create a servlet on a specific URL to handle a HTML post from another server and receive all parameters and their values and insert them into a database.
Got to this code so far:
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
import java.sql.*;
public class QueryServlet extends HttpServlet {
#Override
public void doPost(HttpServletRequest req,HttpServletResponse res) throws IOException, ServletException
{
String instId=req.getParameterValues("instId")[0];
String cartId=req.getParameterValues("cartId")[0];
String desc=req.getParameterValues("desc")[0];
String cost=req.getParameterValues("cost")[0];
String amount=req.getParameterValues("amount")[0];
String currency=req.getParameterValues("currency")[0];
String name=req.getParameterValues("name")[0];
String transId=req.getParameterValues("transId")[0];
String transStatus=req.getParameterValues("transStatus")[0];
String transTime=req.getParameterValues("transTime")[0];
String cardType=req.getParameterValues("cardType")[0];
Connection conn = null;
Statement stmt = null;
PrintWriter out=res.getWriter();
try
{
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "root", "root");
stmt = conn.createStatement();
String sqlStr = "insert into orderdetails values('"+transId+"','"+instId+"','"+cartId+"','"+desc+"'"+cost+"','"+amount+"','"+currency+"','"+name+"','"+transStatus+"','"+transTime+"','"+cardType+")";
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
ResultSet rset = stmt.executeQuery(sqlStr); // Send the query to the server
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
}
I have tried some changes to it and I allways get errors.
Could you give me a hand?
Btw, I have very little knowledge of java, been trying to "hack my way" into doing this from other people examples and from going trough guides.
Thanks in advance
Edit: I can't log into my dev machine atm as it is having problems and is down, it had something to do with Null pointer or Null value, can't give the exact error atm, will update as soon as possible.
I am also aware of the SQL injection with the code, just trying to test it first and make it work and change the code before I set it live.
There where some quote/comma hickups and it should be exevcuteUpdate.
However it is important to use a PreparedStatement:
easier on the SQL string, escapes special chars in the strings (like apostrophe)
you can used typed parameters, like BigDecimal below
security SQL injection
I used the try-with-resources syntax to close the stmt.
String instId = req.getParameter("instId");
String cartId = req.getParameter("cartId");
String desc = req.getParameter("desc");
String cost = req.getParameter("cost");
BigDecimal amount = new BigDecimal(req.getParameter("amount"));
String currency = req.getParameter("currency");
String name = req.getParameter("name");
String transId = req.getParameter("transId");
String transStatus = req.getParameter("transStatus");
String transTime = req.getParameter("transTime");
String cardType = req.getParameter("cardType");
Connection conn = null;
Statement stmt = null;
PrintWriter out = res.getWriter();
try {
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/orders", "root", "root");
String sqlStr = "insert into orderdetails "
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement stmt = conn.prepareStatement(sqlStr)) {
stmt.setString(1, transId);
stmt.setString(2, instId);
stmt.setString(3, cartId);
stmt.setString(4, desc);
stmt.setString(5, cost);
stmt.setBigDecimal(6, amount);
stmt.setString(7, currency);
stmt.setString(8, name);
stmt.setString(9, transStatus);
stmt.setString(10, transTime);
stmt.setString(11, cardType);
int updateCount = stmt.executeUpdate();
out.println("<html><head><title>Query Response</title></head><body>");
out.println("<h3>Thank you for your query. " + updateCount + " record(s) updated.</h3>");
out.println("<p>You query is: " + sqlStr + "</p>"); // Echo for debugging
for (Enumeration<String> en = req.getParameterNames(); en.hasMoreElements();) {
String paramName = en.nextElement();
String paramValue = req.getParameter(paramName);
out.println("<p>" + paramName + ": " + paramValue + "</p>"); // Echo for debugging
}
} // Does stmt.close()
} catch (SQLException ex) {
ex.printStackTrace();
}
For inserting or updating or deleting use executeUpdate() but you are using executeQuery()
and executeUpdate method returns an integer(No.of rows affected) so change
ResultSet rset = stmt.executeQuery(sqlStr);
to
int update= stmt.executeUpdate(sqlStr);
Also prefer to use PreparedStatement

Method that pass parameter to retrieve data from mysql java

I want to create a method when i passed a value to the parameter, it will be passed to the sql statement.
here is what i've tried:
import java.sql.*;
import java.util.*;
import java.text.*;
public class cobadatabase{
protected String sn,fn,ln;
private Connection conn;
private PreparedStatement st;
public cobadatabase(String studentnumber)
{
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentrecords","root","");
st = conn.prepareStatement("SELECT * FROM student WHERE Student_Number=?");
ResultSet rs = st.executeQuery();
while (rs.next()){
sn = rs.getString(1);
fn = rs.getString(2);
ln = rs.getString(3);
SimpleDateFormat ft = new SimpleDateFormat("kk:mm:ss");
ft.format(rs.getTime("Total Time").getTime());
}
}
catch(Exception e){
e.printStackTrace();
}
i don't know what is wrong with my code. I just want to retrieve the data for printing
You haven't set parameter in prepareStatement
st = conn.prepareStatement("SELECT * FROM student WHERE Student_Number=?");
// You need to set the parameter for `?`
st.setString(1, studentnumber); // Add this code in between..
ResultSet rs = st.executeQuery();
And actually that is not a method.. that is a Constructor you are using.. And you are using it for wrong purpose..
Technically, the sole purpose of a Constructor is to initialize the attributes of the object being created, or initialize the environment for use..
For using database query, or doing any other kind of task, you should use a method, and invoke that..
I guess you mean something like that:
public String Func (String par1, String par2) throws SQLException {
String query;
query ="SELECT ... WHERE COLUMN_NAME between +"'"+par1+"'"+" AND " +"'"+par2+"'"+...";
rs = st.executeQuery(query); // get data or just Execute without getting results
Pay attention that Between a String there should be a " '' " (non-doubled quotes), whereas numeric values shouldn't.

MySQL exception - com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException

I get the error:
'Unknown column 'customerno' in 'field list' '.
But, that column exists in my customer table. Then why am I getting this exception ?
Code:
import java.sql.*;
public class Classy {
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
public static void main(String[]args)
{
String username = "cowboy";
String password = "1234567";
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(myQuery);
while(rs.next())
{
System.out.print(rs.getString("customerno"));
}
} catch(SQLException ex){System.out.println(ex);}
}
}
Look at what your query really is. This:
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
is equivalent to:
static String myQuery = "SELECT customerno, nameFROM customers;";
Now can you see what's wrong? I'm surprised it complained about customerno rather than the lack of a FROM part...
Note that I suspect you don't want the ; either. I'd write it all one one line just for readability, when you can, as well as limiting the accessibility and making it final:
private static final String QUERY = "SELECT customerno, name FROM customers";
the problem with your syntax is that you have no space between name and FROM
String myQuery =
"SELECT customerno, name" + // problem is here
"FROM customers;";
instead add a space after name
String myQuery =
"SELECT customerno, name " + // add space here
"FROM customers";
import java.sql.*;
public class Classy {
static String myQuery =
"SELECT customerno, name" +
"FROM customers;";
public static void main(String[]args)
{
String username = "cowboy";
String password = "1234567";
try
{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Business", username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(myQuery);
while(rs.next())
{
//Try and change this with the numeric value that is present in the database,
e.g if it's column 2 do something like
rs.getString(1);
System.out.print(rs.getString("customerno"));
}
}catch(SQLException ex){System.out.println(ex);}
}
}

Categories

Resources