Reputation: 3
Afternoon all,
I'm new to java and programming in general, so what I have so far is somewhat cobbled together from other snippets.
The premise of the class I have is that it will take an input from the user, (eventually via a SOAP service), search the SQL DB and return the relevant row. It will only return one row as the search is on the unique ID.
The below code works as I want it to, I just can't figure out how to code it to accept a string input to search on.
package my.pack;
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;
public class ShowRow {
public ArrayList<String> ShowResults(){
Connection connection = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "******";
String driverName = "com.mysql.jdbc.Driver";
String userName = "******";
String password = "******";
ArrayList<String> rowArray = new ArrayList<String>();
try{
Class.forName(driverName).newInstance();
connection = DriverManager.getConnection(url+dbName, userName, password);
try{
Statement stmt = connection.createStatement();
String selectquery = "SELECT * FROM `thisTable` WHERE `uniqueID` = 12345";
ResultSet rs = stmt.executeQuery(selectquery);
while(rs.next()){
rowArray.add(rs.getString(1));
rowArray.add(rs.getString(2));
rowArray.add(rs.getString(3));
System.out.println(rowArray);
}
}
catch(SQLException s){
System.out.println(s);
}
connection.close();
}
catch (Exception e){
e.printStackTrace();
}
return rowArray;
}
}
The row in question is;
String selectquery = "SELECT * FROM `thisTable` WHERE `uniqueID` = 12345";
Where 12345 would be taken from a user input.
To clarify 'user input' the following class would require an input for 'this' (but has little to do with my question otherwise!);
public class Input {
public String typeHere(String this){
return "You typed " + this;
}
}
Many thanks for your time and help!
Upvotes: 0
Views: 5948
Reputation: 6479
You should pass the user id as parameter to the ShowResults
method and use PreparedStatement
instead of Statement
to prevent SQL Injection attacks.
public ArrayList<String> ShowResults(Integer userId) {
...
...
...
PreparedStatement preStatement = connection.prepareStatement("SELECT * FROM thisTable WHERE uniqueID = ?");
preStatement.setInt(1, userId);
ResultSet rs = preStatement.executeQuery();
...
...
...
}
Upvotes: 1