trying to use search engine using jcombobox - java

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);
}
}
}

Related

RadioButton value Increment decrement using Java

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);
}
}

How can I resolve the error 'Data truncation: Out of range value for column 'id_brand' at row 1'?

I'm working on a Java project with FX and SQL. In this Java project I have a store where I can add products to the database.
Now I also want that I can update a product. I can only update the price of the product but not the brand name and type name. When I want to update the brand name or the type name I receive an error in the console.
This is the code to update a product:
public int editProduct(Double price, int brand, int type, int id) {
String sql = "UPDATE products SET price=?, id_brand=?, id_type=? WHERE id=?";
try {
Class.forName(DRIVER);
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setDouble(1, price);
stmt.setInt(2, brand);
stmt.setInt(3, type);
stmt.setInt(4, id);
int rows = stmt.executeUpdate();
getProducts();
con.close();
return rows;
} catch (ClassNotFoundException | SQLException ex) {
System.out.println("SQL error updaten product");
System.out.println(ex.getMessage());
}
return -1;
}
-
public class EditProductController {
#FXML TextField productId, productBrand, productType, productPrice;
#FXML Label berichtMelding;
#FXML Button saveButton;
private StoreDataAccesObject storeDDA;
public void fill (Product data) {
berichtMelding.setText(Integer.toString(data.getId()));
productType.setText(data.getType());
productBrand.setText(data.getBrand());
productPrice.setText(Double.toString(data.getPrice()));
}
public void updateProductButton() {
storeDDA = new StoreDataAccesObject("noorderpoort", "toets");
ArrayList<String> errorList = new ArrayList<>();
String brand = productBrand.getText();
String type = productType.getText();
String price = productPrice.getText();
String id = berichtMelding.getText();
int idBrand;
int idType;
if (brand.trim().length() <= 0 || type.trim().length() <= 0 || price.trim().length() <= 0) {
errorList.add("Alle velden moeten ingevuld zijn.");
} else {
if (storeDDA.nameExists("brands", brand) > 0) { //checking if brand exists in database.
idBrand = storeDDA.nameExists("brands", brand);
} else {
idBrand = storeDDA.nameExists("brands", brand);
if (idBrand < 0) {
errorList.add("Brand niet opgeslagen");
}
}
if (storeDDA.nameExists("types", type) > 0) {
idType = storeDDA.nameExists("types", type);
} else {
idType = storeDDA.nameExists("types", type);
if (idType < 0) {
errorList.add("Type niet opgeslagen");
}
}
if (storeDDA.editProduct(Double.parseDouble(price), idBrand, idType, Integer.parseInt(id)) <= 0) {
berichtMelding.setText("Product niet geupdate.");
} else {
Stage editProduct = (Stage) saveButton.getScene().getWindow();
editProduct.close();
}
}
if (!errorList.isEmpty()) {
String errorText = "";
for (String error : errorList) {
errorText += error;
}
berichtMelding.setText(errorText);
}
}
}
Tables:
'Data truncation: Out of range value for column 'id_brand' at row 1'?
The data you are trying to store in id_brand does not fit. For example, string might be too long or number too large.
Check the value of unsigned id_brand column if it meets the range.
You have defined the length of id_brand column as 11 and i think you are trying to add value with length more than 11. I reproduced the same error at my end.
create table Test(id integer(11) unsigned);
insert into Test values(1234567891011);
Error:Out of range value for column 'id'ar row 1
And if you are trying to add String value in Integer column then it will not throw the above mentioned error instead it will show:
Incorrect integer value: 'A' for column 'id' at row 1

How to immediate greater and smaller value and select the value?

I have a scenario to take the maximum value from the nearest number and match with that number with .if it is match click action would perform..all conditions I put it in a for loop..
public static int insertBeforeAfterMethod(int i, String event, String shotType, WindowsDriver < WebElement > mainEntrySession) {
for(int cellIndex = 14;cellIndex < pbp_insert_grid_cells.size();cellIndex+=17) //
{
System.out.println(pbp_insert_grid_cells.size());
rowSequenceNo = pbp_insert_grid_cells.get(cellIndex).getText();
String[] splitvalue=rowSequenceNo.split("\\.");
int guiSequenceNo=Integer.parseInt(splitvalue[0]);
System.out.println("hello gui sequence number....."+guiSequenceNo);
//i==4 here i==3
if ((i%2!=0) && (sequenceNo < guiSequenceNo)) //1.5 <2 insert before
{
System.out.println("hello"+i);
next =guiSequenceNo; //2
System.out.println("next"+next);
break;
}
else if((i%2==0) && (sequenceNo > guiSequenceNo)) //insert after
{
previous=guiSequenceNo;
break;
}
if(next==guiSequenceNo) // 2==rowSequenceNo insert before
{
System.out.println(cellIndex);
WebElement sequenceCellNoInsertBefore = mainEntrySession.findElementByName(pbp_insert_grid_cells.get(cellIndex).getAttribute("Name"));
rowNumber = sequenceCellNoInsertBefore.getAttribute("Name").substring(16);
System.out.println(rowNumber);
if(mainEntrySession.findElementByName(rowNumber).isDisplayed())
{
rowToClick = mainEntrySession.findElementByName("Period " +rowNumber);
rowToClick.click();
action.moveToElement(rowToClick).contextClick().perform();
mainEntrySession.findElementByName("Insert Before").click();
mainEntrySession.findElementByAccessibilityId("6").click();
retValue = getNexti(i, event,shotType,mainEntrySession);
System.out.println("return i "+retValue);
}
}
else if(previous==guiSequenceNo) //insert after
{
WebElement sequenceCellNoInsertAfter = mainEntrySession.findElementByName(pbp_insert_grid_cells.get(cellIndex).getAttribute("Name"));
rowNumber = sequenceCellNoInsertAfter.getAttribute("Name").substring(16);
System.out.println(rowNumber);
if(mainEntrySession.findElementByName(rowNumber).isDisplayed())
{
rowToClick = mainEntrySession.findElementByName("Period " +rowNumber);
rowToClick.click();
action.moveToElement(rowToClick).contextClick().perform();
mainEntrySession.findElementByName("Insert After").click();
mainEntrySession.findElementByAccessibilityId("6").click();
retValue = getNexti(i, event,shotType,mainEntrySession);
System.out.println("return i "+retValue);
}
}
}
return retValue;
}
here the for looping is not incrementing it is exiting...without break how to take immediate greater and smaller and store it in a variable...?

SQL Like Query Error

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.)

How to read a List in batches

I have a function which reads a List of Notifications Object. Now I have to read the Notifications object in batches of 100(suppose) and update it.
public boolean addBSInfoToTemp(List<ParentNotification> pNotify)
throws DaoException, BatchUpdateException {
int cnt = 0;
final String query = "insert into Temp values ?,?,?,'Y','N',?,?,?,?";
while (!pNotify.isEmpty()) {
try {
pst = getConnection().prepareStatement(query);
for (ParentNotification pn : pNotify) {
cnt++;
pst.setInt(1, pn.getUserId());
pst.setString(2, pn.getEmail());
pst.setString(3, pn.getNotificationType());
Date createdDate = (Date) pn.getCreatedDate();
pst.setDate(4, createdDate);
pst.setString(5, pn.getCreatedBy());
Date icsesCreatedDate = (Date) pn.getIcsesCreatedDate();
pst.setDate(6, icsesCreatedDate);
pst.setString(7, pn.getMiscellaneous());
pst.addBatch();
if(cnt==batchCount){
break;
}
}
int[] batch = pst.executeBatch();
if (batch.length != 0) {
flag = true;
}
} catch (BatchUpdateException b) {
flag = false;
} catch (SQLException sqlx) {
flag = false;
} finally {
close(pst, null);
}
}
return flag;
}
What I am trying to do is read the List with batchCount = 100 then update and go back to 101 record and then update another 100 records untill the List is empty.
You have this:
while (!pNotify.isEmpty()) {
but I don't see that you ever remove objects from the list, so you have infinite loop. I would just make the outside loop to loop through all of the elements like this:
for (int i=0; i<=pNotify.size(); i++){
// and inside check if it is devisible by batch length
if(i % batchCount == 0){
break;
}
}

Categories