How can I only get 1 element from a SQL Database? - java

I have a small problem. I wrote a method in which I have an SQL query that should output a correct string after 2 parameters. When debugging, however, the result is not the right element. I don't know why this happens.
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
I ask for the username and template_id and I just want to get an element out of the template column.
The SQL query is correct. I've already tested that. But it seems that the query runs through all elements with the same username. As a result, I only get the last element and not the right one.
UPDATE

Currently you do not use the method parameters inside your query. As already suggested you should use a PreparedStatement to fix that. You should basically do the following:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
If you do not use a PreparedStatement and build the query manually as suggested in the comments your application could be vulnerable to SQL injection attacks.

Related

How to pass multiple parameters in sql query using Java?

I have sql query which is shown below its a select statement I want to pass dynamically the values but I am not aware how can we do it .here I want to pass product and location dynamically
can anyone help in this ..
public static ResultSet RetrieveData() throws Exception {
PreparedStatement statement;
String sql = "select * FROM Courses WHERE "
+ "product = product? "
+ "and location = location? ";
System.out.println(sql);
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost:3306/wave1_build";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
statement = con.prepareStatement(sql);
ResultSet rs = statement.executeQuery(sql);
return rs;
One approach is to use plain ? placeholders along with the appropriate setters to bind values:
String sql = "SELECT * FROM Courses WHERE product = ? AND location = ?";
statement = con.prepareStatement(sql);
statement.setString(1, "some product");
statement.setString(2, "some location");
// NOTE: executeQuery() when used with prepared statements does NOT take any parameters
ResultSet rs = statement.executeQuery();

I have written this code for fetch record from my table name is owners... but some error is occurs... is there something missing?

try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mystationary", "root", "");
Statement stmt = con.createStatement();
String qry;
qry = "select * from owners where usernm='" + jTextField1.getText() + "',password='" + jTextField2.getText() + "'";
ResultSet rs = stmt.executeQuery(qry);
while (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
} catch (HeadlessException | ClassNotFoundException | SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
You have to use PreparedStatement instead to avoid any syntax error or SQL Injection:
try (PreparedStatement ps = con.prepareStatement(
"select * from owners where usernm = ? and password = ?")) {
ps.setString(1, jTextField1.getText());
ps.setString(2, jTextField2.getText());
ResultSet rs = ps.executeQuery(qry);
if (rs.next()) {
JOptionPane.showMessageDialog(null, "Welcome '" + jTextField1.getText() + "' !");
}
}
Your real problem is with the , when you want to use where you have to use and not ,
qry = "select * from owners where usernm='"+jTextField1.getText()+"', password='"+jTextField2.getText()+"'";
//------------------------------------------------------------------^
Instead you have to use :
qry = "select * from owners where usernm='"+jTextField1.getText()+"' and password='"+jTextField2.getText()+"'";
//-------------------------------------------------------------------^^^
But PreparedStatement is more secure.
Another thing, if you want to check for one use, then you can use if (rs.next()) instead of while (rs.next())
On this line:
qry = "select * from owners where usernm='"+jTextField1.getText()+"',password='"+jTextField2.getText()+"'";
You are using a comma to separate your conditions when you should be using the SQL operator "AND."
qry = "SELECT * FROM owners WHERE usernm='"+jTextField1.getText()+"' AND password='"+jTextField2.getText()+"'";
Also, as Dave Newton pointed out, this code is vulnerable to SQL injection. And your while loop after the executeQuery() call doesn't actually use your result set.

SQL command from eclipse using JDBC

I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.

ResultSet.next() Throwing SQLException: Result Set Closed

I've tried to debug the code and read the Oracle doc and I don't see any reason why the result set would be closed.
Statement statement = DatabaseConnector.connect();
String sql = "Select * from Room where Room_Type like '*"+roomType+"*' "+availability;
boolean foundResults = statement.execute(sql);
if(foundResults){
ResultSet rs = statement.getResultSet();
StringBuilder row = new StringBuilder();
if(rs!=null){
while(rs.next()){
RE: SQLException
I'm not quite sure what DatabaseConnector is supposed to do in the question code, but the following test code works for me.
RE: Wildcard character
When using the LIKE operator in a query from within the Access application itself then the asterisk * is the wildcard character to use. When querying an ACE (Access) database from some other application one needs to use the "standard" percent % wildcard character. Note that the following code uses %; using * won't work here.
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
"Dbq=C:\\Users\\Public\\Database1.accdb;");
String RoomTypeToMatch = "suite";
PreparedStatement s = conn.prepareStatement(
"SELECT Room_No, Room_Type " +
"FROM Room WHERE Room_Type LIKE ?"
);
s.setString(1, "%" + RoomTypeToMatch + "%");
s.execute();
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("[Room_No]: " + rs.getString(1) +
", [Room_Type]: " + rs.getString(2));
}
}
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
SQL LIKE wildcard charcaters are represented as % not *
String sql =
"Select * from Room where Room_Type like '%"+roomType+ "%' "+availability;
Aside: Always use a PreparedStatement to project against SQL Injection attacks

Problems with PreparedStatement - Java

Im trying to use PreparedStatement to my SQLite searches. Statement works fine but Im getting problem with PreparedStatement.
this is my Search method:
public void searchSQL(){
try {
ps = conn.prepareStatement("select * from ?");
ps.setString(1, "clients");
rs = ps.executeQuery();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
but Im getting this error:
java.sql.SQLException: near "?": syntax error at
org.sqlite.DB.throwex(DB.java:288) at
org.sqlite.NestedDB.prepare(NestedDB.java:115) at
org.sqlite.DB.prepare(DB.java:114) at
org.sqlite.PrepStmt.(PrepStmt.java:37) at
org.sqlite.Conn.prepareStatement(Conn.java:231) at
org.sqlite.Conn.prepareStatement(Conn.java:224) at
org.sqlite.Conn.prepareStatement(Conn.java:213)
thx
Columns Parameters can be ? not the table name ;
Your method must look like this :
public void searchSQL()
{
try
{
ps = conn.prepareStatement("select * from clients");
rs = ps.executeQuery();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
Here if I do it like this, it's working fine, see this function :
public void displayContentOfTable()
{
java.sql.ResultSet rs = null;
try
{
con = this.getConnection();
java.sql.PreparedStatement pstatement = con.prepareStatement("Select * from LoginInfo");
rs = pstatement.executeQuery();
while (rs.next())
{
String email = rs.getString(1);
String nickName = rs.getString(2);
String password = rs.getString(3);
String loginDate = rs.getString(4);
System.out.println("-----------------------------------");
System.out.println("Email : " + email);
System.out.println("NickName : " + nickName);
System.out.println("Password : " + password);
System.out.println("Login Date : " + loginDate);
System.out.println("-----------------------------------");
}
rs.close(); // Do remember to always close this, once you done
// using it's values.
}
catch(Exception e)
{
e.printStackTrace();
}
}
Make ResultSet a local variable, instead of instance variable (as done on your side). And close it once you are done with it, by writing rs.close() and rs = null.
Passing table names in a prepared statement is not possible.
The method setString is when you want to pass a variable in a where clause, for example:
select * from clients where name = ?
thx for replies guys,,,
now its working fine.
I noticed sql query cant hold ? to columns too.
So, this sql query to PreparedStatement is working:
String sql = "select * from clients where name like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "a%");
rs = ps.executeQuery();
but, if I try to use column as setString, it doesnt work:
String sql = "select * from clientes where ? like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, "name");
ps.setString(2, "a%"):
rs = ps.executeQuery();
Am I correct? or how can I bypass this?
thx again

Categories