I have a ResultSet with a sql select query :
ResultSet rst = DB.search("select '"+col+"' from stud where '"+col+"' like '" + S3 + "%'");
In here col = FName(FName is a column);
Here's how FName gets assigned to col :
private void column(){
switch (search_fields.getSelectedItem().toString()) {
case "FName":
col = "FName";
break;
case "MName":
col="MName";
break;
case "LName":
col="LName";
break;
case "DOB":
col="DOB";
break;
case "Address":
col="Address";
break;
case "MotherTP":
col="MotherTP";
break;
case "FatherTP":
col="FatherTP";
break;
case "School":
col="School";
break;
case "Grade":
col="Garde";
break;
case "Email":
col="Email";
break;
}
}
Search_field is a combobox.
There is no error but when I type a First Name(FName) the name of the column FName gets returned.
Here is the Whole Code :
private JTextField txtComboItemName;
private String S3;
private boolean bbb;
private void ComboItemSearch() {
bbb = false;
txtComboItemName = (JTextField) search_txt.getEditor().getEditorComponent();
txtComboItemName.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent evt) {
if (!(
evt.getKeyCode() == KeyEvent.VK_DOWN ||
evt.getKeyCode() == KeyEvent.VK_UP ||
evt.getKeyCode() == KeyEvent.VK_LEFT ||
evt.getKeyCode() == KeyEvent.VK_RIGHT ||
evt.getKeyCode() == KeyEvent.VK_ENTER)) {
try {
S3 = txtComboItemName.getText();
ResultSet rst = DB.search("select '"+col+"' from stud where '"+col+"' like '" + S3 + "%'");
System.out.println("col:"+ col);
boolean b = rst.next();
boolean bb = false;
if (b) {
search_txt.removeAllItems();
bb = true;
}
while (b) {
if (rst.getString(col).startsWith(S3)) {
search_txt.addItem(rst.getString(1));
}
b = rst.next();
}
search_txt.setSelectedItem(S3);
txtComboItemName.setCaretPosition((search_txt.getSelectedItem() + "").length());
search_txt.showPopup();
int i = search_txt.getItemCount();
if (i > search_txt.getMaximumRowCount()) {
search_txt.setMaximumRowCount(1000);
} else {
search_txt.setMaximumRowCount(i);
}
bbb = true;
} catch (Exception ex) {
ex.printStackTrace();
}
} else if (
evt.getKeyCode() == KeyEvent.VK_ENTER &&
bbb == true && evt.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
boolean bIT = false;
String Sr123 = (String) search_txt.getSelectedItem();
try {
ResultSet Rst23 = DB.search("select '"+search_fields.getSelectedItem().toString()+"' from stud");
while (Rst23.next()) {
if (Sr123.equals(Rst23.getString(search_fields.getSelectedItem().toString()))) {
bIT = true;
break;
} else {
bIT = false;
}
}
bbb = false;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
}
At least one problem is the query generated will be as:
select 'COL' from stud where 'COL' like ..
When it should look like
select COL from stud where COL like ..
-- or whatever is appropriate for the database (also note selecting into
-- a well-known column in this second case)
select [COL] as result from stud where [COL] like ..
That is, the column names are incorrectly quoted as strings, and not used as identifiers in SQL.
There are other issues, SQL Injection - as the value supplied to LIKE should be bound by a placeholder, and an over complexity of code, and possibly more.
Consider these additional notes:
List<String> allowedNames = Arrays.asList<String>("FName", ..);
// Ensures the name is valid, or throws an Exception;
// it could also return a normalized name or a boolean, but an
// Exception is the quickest way to ensure "fail fast".
private void assertSearchableColumn(string colName) {
if (!allowedNames.contains(colName)) {
throw new RuntimeException("Invalid column");
}
}
// Then before a particular column is replaced in the SQL command, but there
// is no need to have function that merely sets the global variable.
String col = search_fields.getSelectedItem().toString();
assertSearchableColumn(col);
// Only replace columns, note that the columns are *not* quoted as strings
// in the resulting SQL, and that ? represents "a placeholder".
String sql = String.format("select %s from stud where %s like ?", col, col);
// And then bind the SQL with the appropriate value to use with LIKE.
// (I have no idea what "DB" is or how/if it supports placeholders, however..
// but if it does not already, it *should* support placeholders
// or else it is too easy for SQL Injection, accidental or otherwise.)
Related
this is a online exam system. if the answer is correct marks increment by 1 it is work correctly at the same question second time select wrong answer i i need decrement the value
int marks;
String cor;
public void answerCheck()
{
String answerAnswer="";
if(r1.isSelected())
{
answerAnswer = r1.getText();
}
else if(r2.isSelected())
{
answerAnswer = r2.getText();
}
else if(r3.isSelected())
{
answerAnswer = r3.getText();
}
else if(r4.isSelected())
{
answerAnswer = r4.getText();
}
if(answerAnswer.equals(cor))
{
marks = marks + 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
else if(!answerAnswer.equals(cor))
{
marks = marks - 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
else
{
marks =0;
}
}
i am loading all data from the database correct answer also i am loading
Database Load
public void Connection()
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/onlineex","root","");
String query = "select * from questions";
pst = con.prepareStatement(query);
rs = pst.executeQuery();
while(rs.next())
{
txtqu.setText(rs.getString("id"));
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
cor = rs.getString(7);
}
}
i have a button call next
try
{
if(rs.previous())
{
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
cor=rs.getString(7);
}
else
{
JOptionPane.showMessageDialog(this, "This is first record of student");
}
answerCheck();
}
i have button call previous
if(rs.next())
{
txtques.setText(rs.getString("question"));
r1.setText(rs.getString(3));
r2.setText(rs.getString(4));
r3.setText(rs.getString(5));
r4.setText(rs.getString(6));
cor=rs.getString(7);
}
else
{
JOptionPane.showMessageDialog(this, "This is first record of student");
}
answerCheck();
Firstly there is a Logical error in last else which will never execute because either answer is correct or wrong there is no third condition.
String cor;
public void answerCheck()
{
String answerAnswer="";
if(r1.isSelected())
{
answerAnswer = r1.getText();
}
else if(r2.isSelected())
{
answerAnswer = r2.getText();
}
else if(r3.isSelected())
{
answerAnswer = r3.getText();
}
else if(r4.isSelected())
{
answerAnswer = r4.getText();
}
if(answerAnswer.equals(cor))
{
marks = marks + 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
else if(!answerAnswer.equals(cor) || ((r1.isSelected() ||
r2.isSelected() || r3.isSelected() || r4.isSelected()))
{
marks = marks - 1;
String Marks = String.valueOf(marks);
txtc.setText(Marks);
}
}
I have a problem using getSelectedIndices(). Occassionally, not always, as I have discovered in debug sessions in the database code, it returns an array that includes an index of -1.
Why is that so, and what could I do to prevent this? I want to use this style of logic is various places.
I have a Livestock TableView with SelectionMode.MULTIPLE.
It has a ContextMenu that includes ('Set Breed', 'Set Sex' and 'Set Has Calf')
The logic to set one of these attributes is the same:
The user will, (1) select the relevant rows (using or + mouse-click), then (2) select the relevant MenuItem
This will then invoke setLivestockAttribute() as follows:
private void setLivestockAttribute( String attribute )
{
String value = "";
// 1. Get a List of the Indices of Rows selected.
ObservableList<Integer> selectedIndices = null;
selectedIndices = FXCollections.observableList(tblView_Livestock.getSelectionModel().getSelectedIndices());
// If ONE or MORE rows have been selected.
if ( selectedIndices.size() > 0 )
{
// 2. Get the VALUE of the relevant ATTRIBUTE.
switch (attribute)
{
case LM_Constant.BREED:
value = LM_Utility.getChoice_Breed();
break;
case LM_Constant.SEX:
value = LM_Utility.getChoice_Sex();
break;
case LM_Constant.HAS_CALF:
value = LM_Utility.getChoice_HasCalf();
break;
}
// If there is a VALUE.
if ( value.length() > 0 )
{
ObservableList<LivestockModel> dataList = tblView_Livestock.getItems();
// 3. Update each Livestock record.
DataStore.getInstance().updateLivestock(dataList, selectedIndices, attribute, value);
// 4. Refresh the TableView to show changes.
setLivestockData();
}
}
}
I have decided to:
update the JDK ( as suggested by #sillyfly)
adjust the code to avoid the error (see below)
subscribe to Oracle to receive notices of future upgrades and bug fixes
Code segment ensures database update, ONLY when the index i >= 0.
public boolean updateLivestock(ObservableList<LivestockModel> livestockData, ObservableList<Integer> selectedIndices, String attribute, String value)
{
boolean proceed = true;
boolean updated = false;
int rowCount = 0;
int counter = 0;
String sql = "";
LivestockModel lm;
switch (attribute)
{
case LM_Constant.BREED:
sql = "UPDATE livestock SET (breed, last_updated) = (?, DEFAULT) WHERE rfid = ? AND begin_event = ?";
break;
case LM_Constant.SEX:
sql = "UPDATE livestock SET (sex, last_updated) = (?, DEFAULT) WHERE rfid = ? AND begin_event = ?";
break;
case LM_Constant.HAS_CALF:
sql = "UPDATE livestock SET (has_calf, last_updated) = (?, DEFAULT) WHERE rfid = ? AND begin_event = ?";
break;
}
try ( PreparedStatement preparedUpdate = connection.prepareStatement(sql) )
{
for (Integer i : selectedIndices)
{
if ( proceed != true )
break;
if ( i >= 0 )
{
lm = livestockData.get(i);
preparedUpdate.setString(1, value);
preparedUpdate.setString(2, lm.getRFID());
preparedUpdate.setInt(3, lm.getBeginEvent());
rowCount = preparedUpdate.executeUpdate();
if ( rowCount == 1 )
counter++;
}
else
{
counter++;
LM_Utility.showError_Dialog("Update Livestock", "Index Error", "index = " + i.toString());
}
}
if ( counter == selectedIndices.size() )
{
connection.commit();
updated = true;
}
}
catch (SQLException sqle)
{
LM_Utility.showSQL_Exception("updateLivestock()", sqle);
proceed = false;
}
return updated;
}
In short, the user will input a number (say 1 through 3). This will decide which range of numbers the loop should search through.
switch(input){
case 1:
searchTerm = "i<10 && i>5";
case 2:
searchTerm = "i>=10 && i<19";
case 3:
searchTerm = "i>19 && i<24";
}
while(searchTerm){
//some function
}
Is this possible? I I've not been able to find a way to use a string as search parameters.
EDIT: I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters? For example:
case 1:
searchTerm = "i<5"
case 2:
searchTerm = "i>25 && i<29"
case 3:
searchTerm = "(i<50 && i>25) && (i>55 && i<75)"
case 4:
searchTerm = "(i<20 && i>15) && (i>300 && i<325) && (i>360 && i<380)
Then how does one do it? Multiple loops that call the same function?
The correct way to do this is to not use a string at all:
int min, max;
switch(input){
case 1: // i<10 && i>5
min = 6;
max = 10;
break; // to avoid follow-through to the next case
case 2: // i>=10 && i<19
min = 10;
max = 20;
break;
case 3: // i>19 && i<24
min = 20;
max = 25;
break;
default:
// You need something here in case the value entered wasn't 1-3
}
for (int i = min; i < max; ++i) {
// ...
}
Re your edit:
I don't think I did a very good job of explaining why I needed this. What is one to do if there are different numbers of parameters?
In that case, you'll have to use an expression evaluator (or write one, which is a non-trivial task). There's one in Spring, for instance (not recommending, just happened to hear about it). A search for "Java expression evaluator" should turn up some options.
Another alternative, which is somewhat amusing given that some folks mistook your question for a JavaScript question, is to use the JavaScript evaluator built into Java (either Rhino or Nashorn). E.g.: Live Example
import javax.script.*;
class Ideone {
public static void main(String[] args) throws java.lang.Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
String searchTerm = "i >= 19 && i <= 24";
int i;
try {
i = 19;
engine.put("i", i);
while ((boolean)engine.eval(searchTerm)) {
System.out.println("i = " + i);
++i;
engine.put("i", i);
}
System.out.println("Done");
} catch (ScriptException scriptException) {
System.out.println("Failed with script error");
}
}
}
...but you'll still have the problem of determining what initial value to use for i, which I've hardcoded above.
In Java 8 you can select a lambda instead of String:
Predicate<Integer> searchTerm = (Integer v) -> false;
switch (input) {
case 1:
searchTerm = (Integer v) -> v < 10 && v > 5;
break;
case 2:
searchTerm = (Integer v) -> v >= 10 && v < 19;
break;
case 3:
searchTerm = (Integer v) -> v > 19 && v < 24;
break;
}
while (searchTerm.test(i)) {
...
}
You can create an enumeration as below.
public enum SearchTerms {
None(""),
Between6And9("i<10 && i>5"),
Between10And18("i>=10 && i<19"),
Between20And23("i>19 && i<24");
private final String stringValue;
SearchTerms(String stringValue) {
this.stringValue = stringValue;
}
public String getStringValue() {
return stringValue;
}
public static SearchTerms fromStringValue(String stringValue) {
for (SearchTerms searchTerm : values()) {
if (searchTerm.getStringValue().equalsIgnoreCase(stringValue)) {
return searchTerm;
}
}
return SearchTerms.None;
}
}
Usage:
SearchTerms searchTerm = SearchTerms.fromStringValue("i<10 && i>5");
switch(searchTerm) {
case Between6And9:
//dosomething
break;
}
You can use .eval() of JavaScript.
Also don't forget break; at the end of each case:
Check out this fiddle.
Here is the snippet.
function test(input, i) {
switch (input) { //input=1
case 1:
searchTerm = "i<10 && i>5"; //this will be 'searchTerm'
break;
case 2:
searchTerm = "i>=10 && i<19";
break;
case 3:
searchTerm = "i>19 && i<24";
break;
}
while (eval(searchTerm)) { //'searchTerm' converted to boolean expression
alert(i); // alert for i=7,8,9
i++;
}
}
test(1, 7); //pass input=1 and i=7
The problem is that when I enter some character in JComboBox then it just autoselected, again I enter other text then it replace the first character, so I am not able to type multiple character in JComboBox(my JComboBox is editable)...
pleasw help.
private void combo1KeyReleased(java.awt.event.KeyEvent evt)
{
if((evt.getKeyChar() >= '0' && evt.getKeyChar() <= '9')||(evt.getKeyChar() >= 'a' && evt.getKeyChar() <= 'z')||(evt.getKeyChar() >= 'A' && evt.getKeyChar() <= 'Z')||evt.getKeyCode() == KeyEvent.VK_BACK_SPACE)
{
try
{
Connection con=null;
ResultSet rs;
con=LoginConnection.getConnection();
String srch="";
if(con!=null)
{
srch=(String)combo1.getEditor().getItem();
System.out.println("value to search:"+srch);
String s="select name from supplier where name like '%"+srch+"%' order by name";
PreparedStatement pst=con.prepareStatement(s,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=pst.executeQuery();
int itemCount = combo1.getItemCount();
System.out.println("no of value="+itemCount);
for(int i=0;i<itemCount;i++){ //removing items
combo1.removeItemAt(0);
}
if(!rs.next())
{
System.out.println("----------------------No Data Found");
}
else
{
rs.beforeFirst();
while(rs.next())
{
combo1.addItem(rs.getString(1)); // addind item
System.out.println("while value is:"+rs.getString(1));
}
}
combo1.getEditor().setItem(srch);// adding item in field which i have fetched using getItem method
combo1.showPopup();
}
}
catch(Exception e)
{
System.out.println("ex:"+e);
}
}
}
I'm trying to create a method which checks if the Login (username and password) has a minimum of 6 charakters.
To realize that I created this method public void checkLoginData(final String username, final String password). In that method, I create to booleans (user and pass), with those I can create 4 different boolean-chains:
user: true pass: true
user: false pass: true
user: false pass: false
user: true pass: false
Now I'd like to do a switch/case request for each of them, but I don't get how to realize that...
If you ask why I need the switch, I just think I need it, because I'd like to do for every of those 4 boolean-chains, that it does/show something diffrent. Also I'd like to do this in a sexy-java-way not with tousands of diffrent 'ifs' :P, Please help!
Here's the code of the method:
public void checkLoginData(final String username, final String password){
boolean user, pass;
if (username.length() < 6){
user = false;
}else {
user = true;
}
if (password.length() < 6){
pass = false;
}else {
pass = true;
}
boolean[] logindaten = {user, pass};
}
Thx for the help in Advance!
Best Regards safari
If you really want a "sexy-java-way" (but that depends what you understand as such) you can do something like (Java 7 required):
boolean user, pass;
switch (user + "-" + pass) {
case "false-false":
...
case "false-true":
...
case "true-false":
...
case "true-true":
...
default:
throw new RuntimeException(
"something strange happening here, user: " + user + ",pass: " + pass);
}
but I would prefer to do just 2 distinct checks each with his owns message, the message being joined for presentation. (and not sure if that could be considered "sexy-java-way", more like a 'workaround')
You can't switch over boolean[], only over integral types. To convert the booleans to an int, you could use a bit mask for the 2 booleans, like for example this:
int val = 0;
if (user) val |= 0x1;
if (pass) val |= 0x2;
switch (val) {
case 0: // Both too short
case 1: // User Ok, pass too short
case 2: // User too short, pass ok
case 3: // Both Ok
}
Guess thats how I would solve it with enums:
public class LoginController
{
private void login( String username, String password )
{
LoginState state = determineLoginState( username, password );
switch ( state )
{
case LOGIN_OK:
//Do Something
break;
case USERNAME_FALSE:
//Do Something
break;
case PASSWORD_FALSE:
//Do Something
break;
case BOTH_FALSE:
//Do Something
break;
}
}
private LoginState determineLoginState( String username, String password )
{
final boolean checkUsername = checkUsername( username );
final boolean checkPassword = checkPassword( password );
if ( checkUsername && checkPassword )
return LoginState.LOGIN_OK;
if ( !checkUsername && checkPassword )
return LoginState.USERNAME_FALSE;
if ( checkUsername && !checkPassword )
return LoginState.PASSWORD_FALSE;
if ( !checkUsername && !checkPassword )
return LoginState.BOTH_FALSE;
throw new AuthenticationException();
}
protected boolean checkUsername( String username )
{
return username.length() > 6;
}
protected boolean checkPassword( String password )
{
return password.length() > 6;
}
private enum LoginState
{
LOGIN_OK, USERNAME_FALSE, PASSWORD_FALSE, BOTH_FALSE;
}
public class AuthenticationException extends RuntimeException
{
}
}
Basically there is no simpler way than this, and no way to do it in significantly less lines of code.
if (username.length() < 6){
if (password.length() < 6){
// do case 1
} else {
// do case 2
}
} else {
if (password.length() < 6){
// do case 3
} else {
// do case 4
}
}
To my mind, that makes this the best solution.
Also I'd like to do this in a sexy-java-way not with tousands of diffrent 'ifs'
If by "sexy-java-way" you mean "clever" or "obscure", then there are other ways to do it. But they certainly don't make the code easier to read / more maintainable.
By the way, the above involves only 3 ... that's right THREE ... if statements.
However your (final) specific example:
public void checkLoginData(final String username, final String password){
boolean user, pass;
if (username.length() < 6){
user = false;
}else {
user = true;
}
if (password.length() < 6){
pass = false;
}else {
pass = true;
}
boolean[] logindaten = {user, pass};
....
}
can be simplified to the following:
public void checkLoginData(final String username, final String password){
boolean user = username.length() >= 6;
boolean pass = password.length() >= 6;
boolean[] logindaten = {user, pass};
....
}
Note that simplification is possible here because the actions (the "cases" in your hypothetical switch) can be refactored into simple boolean assignments AND the tests are actually independent of each other. In general you can't do that ...
... but id like to have it more celver to impress my boss ;)
Seriously, if I was your boss and you wrote code like that, I'd be UN- impressed. Any boss who thinks you are clever for writing obscure and unmaintainable code is clueless.
if (user) {
if (pass) {
// user = true, pass = true
} else {
// user = true, pass = false
}
} else {
if (pass) {
// user = false, pass = true
} else {
// user = false, pass = false
}
}
Or
int case = user ? (pass ? 1 : 2) : (pass ? 3: 4);
switch (case) {
case 1:
System.out.println(" user = true, pass = true ");
break;
case 2:
System.out.println(" user = true, pass = false ");
break;
case 3:
System.out.println(" user = false, pass = true ");
break;
case 4:
System.out.println(" user = false, pass = false ");
break;
}
}
You can do something like this and then each case is 1,2 or 3, etc.
switch((route.isComplete()?1:(route.getAuthentic()?2:(route.hasRoute()?3:0)))) {...}
With java12, you can use expressions within switch-case and provide a Bool type (https://blog.codefx.org/java/switch-expressions/).
private static boolean checkCharOf_(String userName){
return userName.length() >= 6;
}
private static boolean checkCharOf_(String password){
return password.length() >= 6;
}
or
private static boolean checkCharOf_And_(String userName, String password){
return userName.length() >= 6 && password.length() >= 6;
}