Thursday, 5 September 2013

Java how to search SQL from user input to method

Java how to search SQL from user input to method

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!

No comments:

Post a Comment