I am trying to use the user's selection of a JRadioButton as part of a SELECT query for a derby database. For some reason, when I click the search button (called diffSearchbtn), nothing happens. What should be happening is that the SELECT query puts all the entries that match the criteria of the radio button into a JTable on a panel called dispPanel.
Here is the code for the method that assigns a string based on what button the user clicks.
private String tagValid()
{
String diff = "";
if (dEasybtn.isSelected())
{
diff = "EASY";
System.out.println("easy");
}
else if (dMedbtn.isSelected())
{
diff = "MEDIUM";
System.out.println("medium");
}
else if (dHardbtn.isSelected())
{
diff = "HARD";
System.out.println("hard");
}
else
{
diff = null;
}
return null;
}
Here is the code that is meant to display the form:
private void diffSearchbtnActionPerformed(java.awt.event.ActionEvent evt) {
if(tagValid()!=null)
{
String q = String.format("Select* from Gabby.PData where DIFFICULTY = '%d'", tagValid());
ResultSet res = Backend.query(q);
guiTable.setModel(DbUtils.resultSetToTableModel(res));
int counter = 3;
try
{
while (res.next()) {
counter++;
System.out.println("increasing counter");
}
}
catch (SQLException ex) {
Logger.getLogger(WikiPlantGUI.class.getName()).log(Level.SEVERE, null, ex);
}
if (counter == 0)
{
basePanel.removeAll();
basePanel.add(NoMatchPanel);
basePanel.repaint();
basePanel.revalidate();
}
else
{
basePanel.removeAll();
basePanel.add(dispPanel);
basePanel.repaint();
basePanel.revalidate();
}
}
}
Here is the code from the class Backend:
public static ResultSet query(String q)
{
try {
System.out.println("a query");
Statement stat = myConObj.createStatement();
ResultSet res = stat.executeQuery(q);
return res;
}
catch (SQLException e)
{
e.printStackTrace(); // tells what the error is
return null; // returns nothing
}
}
GUI screenshot
There are no error messages, and the program otherwise runs perfectly. Any idea on what's going wrong?
Related
i am trying to making an update button in my GUI form that can be edit a record in my DB but i missing something that i hope someone to help me
this the code of update method:
public int updateUser(Login user) //int
{
DatabaseConnection dbconn = new DatabaseConnection();
Connection conn = dbconn.getConn();
int rows = 0;
try
{
String sql = "UPDATE LOGIN set USER_NAME = ? , PASSWORD = ? , PRIVILEGE_ID = ?";
PreparedStatement pStm = conn.prepareStatement(sql);
//fill SQL parameters from user: //
pStm.setString(1, user.getUserName());
pStm.setString(2, user.getPassword());
pStm.setInt(3, user.getPrivilegeId());
rows =
pStm.executeUpdate();
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
finally
{
try {
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());;
}
}
return rows;
}
code in java swing for update button:
private void updateUserLayerActionPerformed(java.awt.event.ActionEvent evt) {
// 1-get data from user and check it: //
String _name = nameLayer.getText().trim();
String _paswrd = passLayer.getText().trim();
String _prvName = privLayer.getSelectedItem().toString();
//get Privilege_Id from DB:
PrivilegeHandeler prvHndler = new PrivilegeHandeler();
int prvId = prvHndler.getPrivilegeByName(_prvName);
if(_name.length() >0 && _paswrd.length() >0 && prvId> 0)
{
Login user = new Login();
user.setUserName(_name);
user.setPassword(_paswrd);
user.setPrivilegeId(prvId);
//update User: //
loginHandeler loghndlr = new loginHandeler();
int rows =
loghndlr.updateUser(user);
if (rows >0)
{
usrFormErorr.setText("user has been added successfully :)");
nameLayer.setText("");
passLayer.setText("");
privLayer.setSelectedIndex(0);
}
else
{
usrFormErorr.setText("updated failed, try again");
}
}
else
{
usrFormErorr.setText("please, fill the required fields first");
}
}
My problem is this:
1-i am trying to enter an info to edit then update but always get an error updated failed, try again that i made it to get a message when there is a problem
Kindly help. A working code would be very highly appreciated. Thanks in advance.
I am creating a java application to generate questions, and the method shown below is used to generate the questions. I have used a stack to order these questions by how many times they have appeared in the loop.
My problem is that it keeps producing multiple questions which are the same, which this method should prevent.
public ArrayList<String> generateQuestions(String transcript, String className, int classYear, String classGroup) {
ArrayList<String> results = new ArrayList<String>();
ArrayList<String> tags = new ArrayList<String>();
//get tags from the database
Statement stmt = null;
try {
stmt = handler.getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt != null){
try {
String result = "";
ResultSet rs = stmt.executeQuery("SELECT tags.TagName FROM class, tags, questtag, questions, questclass WHERE questtag.QuestionID = questions.QuestionID AND tags.TagID = questtag.TagID AND questions.QuestionID = questclass.QuestionID AND questclass.ClassID = class.ClassID AND class.ClassName ='"+className+"' AND class.ClassYear="+classYear+" AND class.ClassGroup ='"+classGroup+"' GROUP BY tags.TagID");
while (rs.next()) {
result = rs.getString(1);
tags.add(result);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Stack<Question> stack = new Stack<Question>();
for (String word : transcript.split("\\s+")) {
if( ! word.equalsIgnoreCase("the") || ! word.equalsIgnoreCase("I")) {
for(String tag : tags) {
if(word.equalsIgnoreCase(tag)) {
try {
stmt = handler.getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt != null){
try {
String result = "";
ResultSet rs = stmt.executeQuery("SELECT questions.Question FROM class, tags, questtag, questions, questclass WHERE questtag.QuestionID = questions.QuestionID AND tags.TagID = questtag.TagID AND questions.QuestionID = questclass.QuestionID AND questclass.ClassID = class.ClassID AND class.ClassName ='"+className+"' AND class.ClassYear="+classYear+" AND class.ClassGroup ='"+classGroup+"' AND tags.TagName = '"+tag+"'");
while (rs.next()) {
result = rs.getString(1);
Stack<Question> searchStack = new Stack<Question>();
boolean multiple = false;
if(stack.isEmpty()) { //1st question we've come to
Question question = new Question(result);
stack.push(question);
} else {
while(multiple == false && !stack.isEmpty()) {
//search through the stack
searchStack.push(stack.pop());
//if question is not already in the stack
if(((Question)searchStack.peek()).getQuestion().equalsIgnoreCase(result)) {
//then it is multiple
//add one to its noOfTimes
((Question)searchStack.peek()).addToNoOfTimes();
//order this above others with lower score
if(!stack.isEmpty()) {
if(((Question)stack.peek()).getNoOfTimes() < ((Question)searchStack.peek()).getNoOfTimes()) {
Question thisQuestion = searchStack.pop();
while(((Question)stack.peek()).getNoOfTimes() < thisQuestion.getNoOfTimes() && !stack.isEmpty()) {
searchStack.push(stack.pop());
}
stack.push(thisQuestion);
} else {
stack.push(searchStack.pop());
}
}
multiple = true;
}
}
while(!searchStack.empty())
stack.push(searchStack.pop());
if(multiple == false) {
Question question = new Question(result);
stack.push(question);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Stack<Question> reorderStack = new Stack<Question>();
while(!stack.empty()) {
reorderStack.push(stack.pop());
}
while(!reorderStack.empty()) {
Question thisQuestion = reorderStack.pop();
results.add(thisQuestion.getQuestion());
stack.push(thisQuestion);
}
}
}
}
}
}
return results;
}
I am trying to pass data from a db in another class into JFrame in jcombobox but only the last row is displayed. Below is a sample code:
Class A...
public String jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
while (rs.next()) {
customer = (rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return customer;
}
Class JFrame...
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
this.jCBCustomers.addItem(app.jcbNames());
}
the problem is there you return just one String in your jcbNames method , use an arraylist and add all of strings to it and then return it as a collection of database data.
so change your methods or use this modified methods.
public ArrayList<String> jcbNames() {
try {
con = connCC.getDBconnection();
stm = con.createStatement();
ResultSet rs = stm.executeQuery("Select customerName From appointment");
ArrayList<String> list = new ArrayList<>();
while (rs.next()) {
list.add(rs.getString(1));
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Appointment.class.getName()).log(Level.SEVERE, null, ex);
}
return list;
}
and
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
this.jCBCustomers.removeAllItems();
ArrayList<String> list =app.jcbNames();
for (String str:list){
this.jCBCustomers.addItem(str);
}
}
and if you don't want to use this.jCBCustomers.removeAllItems(); to prevent duplicates , use below code
private void jCBCustomersActionPerformed(java.awt.event.ActionEvent evt) {
Appointment app = new Appointment();
// collect all of your current data in jcombobox
ArrayList<String> current_list = new ArrayList<>();
int count = this.jCBCustomers.getItemCount(); // get count of them
for (int i = 0; i < count; i++) {
current_list.add((String) this.jCBCustomers.getItemAt(i)); // add them to current list
}
// data that returned from database
ArrayList<String> returned_from_db_list = jcbNames(); // calling jcbNames method
/*
for each string that has returned from database ,
if it doesn't in the current_list
you can add it to jcombobox , so ...
*/
for (String str : returned_from_db_list) {
if ( !current_list.contains(str) ) { // check for existing in the current_list
current_list.add(str); // adding fresh data to current_list!
/*
or you can add them directly to jcombobox and remove above statement.
this.jCBCustomers.addItem(str); // add updated data to jcombobox
*/
}
}
/*
if ::: you use current_list.add(str); in above for-each-loop ,
now you must update jcombobox data !
else ::: remove below loop.
*/
for (String singleStr : current_list) {
this.jCBCustomers.addItem(singleStr); // add updated data to jcombobox
}
}
I want to make website blocker in my web browser, so I made a database which contain the names of website. Now I want to check the string from database with indexOf method, but it is giving me an error while I am trying to check. Please tell me where my mistake is. Rest of the code is correct and working only database part is not working.
public void loadURL(final String url) {
try {
Connection myconnection;
myconnection = DriverManager.getConnection("jdbc:mysql://localhost/bookmarks", "roo t", "");
try {
String q = "select * from block where url=?";
PreparedStatement mysat = myconnection.prepareStatement(q);
ResultSet myresult = mysat.executeQuery();
int index1;
while (myresult.next()) {
String s2 = myresult.setString("url");
String s1 = txtURL.getText();
index1 = s1.indexOf(s2);
}
if (index1 == -1) {
JOptionPane.showMessageDialog(rootPane, "You Cannot access this website", "Error", JOptionPane.ERROR_MESSAGE);
} else {
Platform.runLater(new Runnable() {
#Override
public void run() {
String tmp = toURL(url);
if (tmp == null) {
tmp = toURL("http://" + url);
}
engine.load(tmp);
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
myconnection.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if you use PreparedStatement you have to set a
value for each ? marker:
String q="select * from block where url=?";
PreparedStatement mysat=myconnection.prepareStatement(q);
mysat.setString(1,"www.google.com");
without you have an invalid sql syntax.
First I create a search function in my program and I implemented the same logic in adding data into the database but the search function works and the add function didn't (SQLException). I created a table from DB2 named Names with only one column FullName. Do you still need to create a new query to add data into the table? or not? I want to add data into the database through GUI.
Here is my Java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class ConnectAndSearchDB extends JFrame implements ActionListener
{
private JTextField fieldSearch,fieldAdd;
private JButton searchB,addB;
private Connection connection;
private String name;
private ResultSet rs,rs1;
public ConnectAndSearchDB() throws SQLException,ClassNotFoundException
{
setLocationRelativeTo(null);
setDefaultCloseOperation(this.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,2));
fieldSearch = new JTextField(20);
searchB = new JButton("Search");
fieldAdd = new JTextField(20);
addB = new JButton("Add");
add(searchB);
add(fieldSearch);
add(addB);
add(fieldAdd);
searchB.addActionListener(this);
addB.addActionListener(this);
establishConnection();
pack();
setResizable(false);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object act = e.getSource();
if(act.equals(searchB))
{
name = fieldSearch.getText();
searchData();
}else if(act.equals(addB))
{
try {
addData();
} catch (ClassNotFoundException e1)
{
e1.printStackTrace();
System.out.println("ClassNotFound");
} catch (SQLException e1)
{
e1.printStackTrace();
System.out.println("SQLError");
}
}
}
public void establishConnection() throws SQLException , ClassNotFoundException
{
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection("jdbc:db2://localhost:50000/COLINN", "Colinn","ezioauditore");
}
private void searchData()
{
try
{
PreparedStatement s = null;
String query;
query = "SELECT * from NAMES";
s=connection.prepareStatement(query);
rs = s.executeQuery();
boolean matchfound = false;
while(rs.next())
{
if(rs.getString(1).equals(name))
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
break;
}
}
if(matchfound == false)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public void addData() throws ClassNotFoundException,SQLException
{
PreparedStatement ps = null;
String query;
query = "INSERT INTO NAMES VALUES('"+fieldAdd.getText()+"')";
ps = connection.prepareStatement(query);
rs1 = ps.executeQuery();
System.out.println("Written Successfully");
}
public static void main (String args[]) throws SQLException,ClassNotFoundException
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
new ConnectAndSearchDB();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Here is the Names table:
I highly suspect that using rs1 = ps.executeQuery(); to insert/update the database is the course of your issue, you should be using int count = ps.executeUpdate();
See PreparedStatement#executeUpdate for more details
Not an answer per se, but a series of extended comments about some issues with the overall approach...
Lesson #1 - Resource management
If you open it, you should close it...
String query = "SELECT * from NAMES";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
try (ResultSet rs = s.executeQuery()) {
boolean matchfound = false;
while(rs.next())
{
if(rs.getString(1).equals(name))
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
break;
}
}
if(matchfound == false)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
See The try-with-resources Statement for more details...
I'd also reconsider using a single Connection, while a Connection pool might be overkill for this problem, you could simply open and close a Connection as need, but remember, there is an overhead incurred when doing this...
Lesson #2 - Don't do what the database can do better
String query = "SELECT count(*) from NAMES where name=?";
try (PreparedStatement stmt = connection.prepareStatement(query)) {
stmt.setString(1, name);
try (ResultSet rs = s.executeQuery()) {
boolean matchfound = false;
if (rs.next())
{
if(rs.getLong(1) > 0)
{
matchfound = true;
System.out.println("The name "+name+" is found in the Database");
}
}
if(!matchfound)
{
System.out.println("Match Not Found");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Lesson #3 - Make use of your PreapredStatement...
Instead of...
query = "INSERT INTO NAMES VALUES('"+fieldAdd.getText()+"')";
Use...
query = "INSERT INTO NAMES VALUES(?)";
//...
ps.setString(1, fieldAdd.getText());
See Using Prepared Statements