I have a code as follow:
String query = "select * from EmployerData where userName = ? and password = ?";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1, textField.getText()); // what 1 refers to
pst.setString(2, passwordField.getText()); // 2
which is working perfectly as I want but I get confused about the meaning of parameterIndex. What does parameterIndex mean???
It tells the query which question mark to replace. The first question mark - index 1. The second question mark - index 2.
Related
I have asked this beacause i was not able to find the answer.
what i am doing is
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE diseaseName =""+diseaseName +'" AND name = '"+username+"'";
it is perfecty running unless and until diseases does not contain 's type of word like
Wilms' tumor
Addison's disease
etc....
so query like
SELECT * FROM diseaseinfo WHERE diseaseName = 'Adult Still's disease' AND name = 'add';
wont execute because of ' 's on 'Adult Still's
and also in java i cant start string with String selectTableSQL = ' '; it will always be in String selectTableSQL = " ";
any solution?
To avoid this case and any syntax error or SQL Injection you have to use PreparedStatement instead :
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE col1 = ? and col2 = ?";
try (PreparedStatement ps = connection.prepareStatement(selectTableSQL)) {
ps.setString(1, value_1);
ps.setString(2, value_2);
ResultSet rs = ps.executeQuery();
while(rs.next()){
//...
}
}
The correct way to use queries in JDBC is to use PreparedStatement and bind variables.
But in your case, try replacing the single quotes ' in your values with \'.
You can use a simple diseaseName.replace("'", "\\'"); to do it.
This question already has answers here:
java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0) [closed]
(2 answers)
Closed 6 years ago.
try {
int stupac=tabZaDijagnozu.getSelectedRow();
String T=(tabZaDijag.getModel().getValueAt(stupac,0).toString());
String sql="SELECT *FROM dijagnoze WHERE ID='"+T+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()) {
String id=rs.getString("ID");
String Query = "DELETE *FROM dijagnoze WHERE ID='"+id+"'";
pst=conn.prepareStatement(Query);
pst.setString(1, "ID");
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted!");
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
I tried to figure it out by myself looking into other similar posts but it just didnt work.
You do not have any parameters in your SQL. In your code you are building the SQL but appending the value
Change to
String Query = "DELETE FROM dijagnoze WHERE ID = ?";
pst=conn.prepareStatement(Query);
pst.setString(1, id);
edit
Also, your select should be fixed at least to the below (but using parameters would be safer to protect from sql injection)
String sql="SELECT * FROM dijagnoze WHERE ID = '" + T + "'";
edit2
In your code you are firstly doing a select based upon id, then if that record exists, you are doing a delete. It is not necessary to so the select first, just delete.
I keep getting this error when trying to connect to the database.
This is my prepared statement
String SQL = "SELECT * FROM `?` WHERE `HomeTeam` = '?'";
PreparedStatement prepst;
prepst = con.prepareStatement(SQL);
prepst.setString(1,box1.getSelectedItem().toString());
prepst.setString(2,box1.getSelectedItem().toString());
rs = prepst.executeQuery();
Anyone know why I get this error?
I think that your problem is in ' and ``` symbols. You should fix the sql as follwing:
String SQL = "SELECT * FROM ? WHERE HomeTeam = ?";
However I am not sure that parameter placeholder ? is supported after from. So, propbably you will have to put it yourself, e.g.:
String table = box1.getSelectedItem().toString();
String SQL = "SELECT * FROM " + table + " WHERE HomeTeam = ?";
Use
String SQL = "SELECT * FROM ? WHERE HomeTeam = ?";
Don't use ` to nest parameters, use ' to nest values you're comparing against if you're hard coding them.
You can't use ? to specify a table name.
I am updating table using PreparedStatement
the following code works perfectly
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname = 'java10'");
int i = pst.executeUpdate();
but when i tried like this it throwing exception
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(2, "java10"); // yeah second column is jfname
int i = pst.executeUpdate();
stacktrace :
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5330)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5318)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setString(OraclePreparedStatementWrapper.java:282)
at com.indus.database.EmployeeDTO.updateData(EmployeeDTO.java:114)
2 in following refers to the position of the question mark in query string, not to the position of column in database table and not to the order of column names used in query:
pst.setString(2, "java10"); // yeah second column is jfname
Use 1 instead.
pst.setString(1, "java10"); // first question mark is jfname
Please go through the setString() method specs:
http://docs.oracle.com/javase/1.4.2/docs/api/java/sql/PreparedStatement.html#setString%28int,%20java.lang.String%29
The correct approach is :
pst = conn.prepareStatement("UPDATE playjdbc SET jlname ='javafx10new' WHERE jfname =?");
pst.setString(1, "java10");
int i = pst.executeUpdate();
I am trying to use a SQL Select statement for a query in Java. I currently have the following:
ResultSet rs = stmt.executeQuery("SELECT *" +
" FROM " + table +
" WHERE " + selection +
" VALUES " + selectionArgs);
where "selection" is a string and "selectionArgs" is a string array.
String selection = "documentFK=?";
String[] selectionArgs = { ... };
Is it possible to use the VALUES command to replace the ? like in with the INSERT command? Either way, what would be the correct syntax?
Thanks for the help.
I believe what you're looking for is the IN statement. Your query should look like this:
SELECT *
FROM table
WHERE documentFK IN ('doc1', 'doc2', 'doc3')
AND userFK IN ('user1', 'user2', 'user3')
This is (obviously) going to make your code a bit more ugly. You'll have to ensure that the WHERE keyword is used for the first clause, but the AND keyword is used for every other clause. Also, each list will have to be comma-delimited.
no, that is not the way it's done. first you create the statement from the query, using the question marks as place holders for the real values you want to put there. then you bind these values to the statement.
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE documetFK = ?";
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the value
stmt.setInt(1, 4); //1 is "the first question mark", 4 is some fk
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
now, if you want this thing with selection string and some args, then you're going to have a loop in your java code. not sure what your array looks like (you're not giving me that much to go on), but if it's made up from strings, it would be something like this:
//the query
String sql = "SELECT " + "*" +
" FROM " + table +
" WHERE " + selection;
//create the statement
PreparedStatement stmt = connection.prepareStatement(sql);
//bind the values
for(int i = 0; i < selectionArgs.length; i++) {
stmt.setString(i, selectionArgs[i]); //i is "the nth question mark"
}
//execute the query and get the result set back
ResultSet rs = stmt.executeQuery();
Can you use a PreparedStatement?
First of all SELECT .. WHERE .. VALUES is incorrect SQL syntax. Lose the VALUES part.
Then you're looking for prepared statements.
In your example it's going to look something like this:
String sql = "SELECT * FROM myTable WHERE documentFK=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
ResultSet rs = pstmt.executeQuery();
Or with multiple parameters:
String sql = "SELECT * FROM myTable WHERE documentFK=? AND indexTerm=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "myDocumentFK"); // parameters start from 1, not 0. also we're assuming the parameter type is String;
pstsm.setInt(2, 100); // assume indexTerm can be 100 and is an integer
ResultSet rs = pstmt.executeQuery();
However, all of this doesn't worth your while since you can simply do the same by concatenating the value into the statement. But be aware of the SQL injections, so don't forget to escape the parameters that you're passing into the database.
PS: I was typing this way too long. You already have the answers :-)
As a side note, you may want to take a look at this to prevent SQL injections:
https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
Sormula can select using "IN" operator from a java.util.Collection of arbitrary size. You write no SQL. It builds the SQL SELECT query with correct number of "?" parameters. See example 4.