Cannot fill Jcombobox from database in java - java

I'm Trying to get Information from a database to fill a Jcombobox, I'm trying to use the following codes but they are not working, in all of them the combo box is not being cleaned when.
Fisrt Attempt
try {
con = Connectionz.getConnection();//Connection Object
pst = con.prepareStatement("SELECT * AS achooserfill FROM Login_Users WHERE [C Team Lead] =?");
pst.setString(1, va);
rs = pst.executeQuery();
while (rs.next()) {
achooser.removeAll();
achooser.addItem("Please select agent");
achooser.addItem(rs.getString("achooserfill"));
}
}catch(Exception e){
System.err.println(e);
}
Second Attempt
try {
con = Connectionz.getConnection();//Connection Object
pst = con.prepareStatement("SELECT * FROM Login_Users WHERE [C Team Lead] =?");
pst.setString(1, va);
rs = pst.executeQuery();
while (rs.next()) {
achooser.removeAll();
achooser.addItem("Please select agent");
achooser.addItem(rs.getString("[VA #]"));
}
}catch(Exception e){
System.err.println(e);
}
Third Attempt
try {
con = Connectionz.getConnection();//Connection Object
pst = con.prepareStatement("SELECT [VA #] FROM Login_Users WHERE [C Team Lead] =?");
pst.setString(1, va);
rs = pst.executeQuery();
while (rs.next()) {
achooser.removeAll();
achooser.addItem("Please select agent");
achooser.addItem(rs.getString("[VA #]"));
}
}catch(Exception e){
System.err.println(e);
}
In all of the cases the result is the same,
I Would really appreciate any kind of info or any resource to fix the situation

in all of them the combo box is not being cleaned.
achooser.removeAll();
The removeAll() method is a method of the Container, not the combo box.
You want:
achooser.removeAllItems();
to remove the items from the combo box.
And that statement should be outside of the loop.
Also, for something like this did you even verify that your ResultSet contains data. First you should just hardcode the data to prove that the addItem() method works. Then once you know that logic is working you make the code more dynamic by getting the data from the database.

I like #camickr's comment, so am revising my answer. Try populating the model from the resultset, then declaring the JComboBox:
MutableComboBoxModel model = new DefaultComboBoxModel();
while (rs.next()){
model.addItem(rs.getString("achooserfill"));
}
JComboBox achooser = new JComboBox(model);

Related

Java - get the value of selected list item

how can I get the value of an list?
This are my two lists and after selecting these two values from the list(as marked) I want to insert these two elements(strings) into my database at this postition in my code:
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, txtFieldName.getText());
pst.setString(2, txtFieldNumber.getText());
// pst.setString(3, listDay.);
And at the last position I want to select the value which the user selects in the UI two list :
JButton btnNewButton_2 = new JButton("Speichern");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.sql.Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/dblabor","root","");
String query = "INSERT INTO Teach(Prof,Laborname,Room,Day,Time) VALUES(?,?,?,?,?)";
PreparedStatement pst = con.prepareStatement(query);
pst.setString(1, txtFieldName.getText());
pst.setString(2, txtFieldLaborname.getText());
pst.setInt(3, Integer.parseInt(txtFieldRoom.getText()));
pst.setString(4, (String) listDay.getSelectedValue());
pst.setString(5, (String) listTime.getSelectedValue());
pst.execute();
pst.close();
JOptionPane.showMessageDialog(null, "Succssesfull");
}
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "Wrong");
}
`
Thank you all in advance.
how can I get the value of an list?
You have been told to simply use:
Object value = list.getSelectedValue();
System.out.println(value);
Did you display the value?
Have you read the tutorial on JDBC Database Access?
I believe you need to use executeUpate() method of the PreparedStatement to change the data.
If you are using Swing, try method javax.swing.JList#getSelectedValue to get value from JList object.

How to check if the inputted data exist in database

I would like to know if what am I lacking here, I can't compare the 'id' from the Textfield to the data from the database.
For example:
If TextField1 == to the data in the database.
Output: Swept by GSW.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list WHERE id = ?";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
}
}
}catch(SQLException exc){
System.out.println("Not Found!");
}
Kindly Check the Image Output.
I attached the image file below.
Sample Output
Here are some mistake I see
You use a parameter in the query, "SELECT * FROM item_list WHERE id = ?";so use a PreparedStatement
Set the parameter to that PreparedStatement ps = connection.preparedStatement(query); with ps.setInt(1, Integer.parseInt(TF[0].getText()));
Don't catch the exception without logging it, here your query as a syntax error but you don't know it.
careful with uppercase in the database field name "Id"
This might not be everything ...
And of course, now that you get only the row with that ID, you can simply check if there is at least one row return to validate that it exists.
First of all, you need to log a stack trace of an exception that is thrown. At least you can use exc.printStackTrace() in your catch section.
Second, your issue is that you declared a parameter for your SQL query, but you have not put any value to it.
PreparedStatement p = con.prepareStatement("SELECT * FROM item_list WHERE id = ?");
p.setString(1, TF[0].getText() ); //VALUE_FROM_YOUR_TEXT_INPUT
You don't need to iterate over all result set to check if a user with such id exists. You can just check that result set is not empty.
you can use intValue() for Integer object obvious if your object is not null
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()).intValue() == id){
System.out.println(id);
}
}
You're not setting the value of the id parameter in the statement. Not familiar with Java but in C# it would be something like
statement.Parameters.AddWithValue("#id", id)
Thank You guys! I've been trying and reading all your suggestions, and I've found and debugged it. Thanks to the one said that I need to check what message I can get in the catch.
Appreciated all your help.
Connection con = connect.getConnection();
String query = "SELECT * FROM item_list";
Statement st;
ResultSet rs;
int id;
try{
st = con.createStatement();
rs = st.executeQuery(query);
while(rs.next()){
id = rs.getInt("id");
if(Integer.parseInt(TF[0].getText()) == id){
System.out.println(id);
JOptionPane.showMessageDialog(null, "FOUND!");
}
else{
JOptionPane.showMessageDialog(null, "Not Found!");
}
}
}catch(SQLException exc){
JOptionPane.showMessageDialog(null, exc.getMessage());
}
ID Found!

Can have two database connection in one function?

When I debug, I get this error :
Column 'place1' not found.
I was able to verify that it has column place1 in sql.
Is it because I can not have two database connection in one function? I am unsure on how to further debug the problem.
Case.java
System.out.println("The highest value is "+highest+"");
System.out.println("It is found at index "+highestIndex+""); // until now it works fine
String sql ="Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
int kb=rs.getInt("Day");
System.out.println(kb);
if(kb==k) // k is a value getting from comboBox
{
String sql1 ="Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 =db1.getConnection();
PreparedStatement ps1 = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs1 = ps.executeQuery();
if (rs1.next())
{
String aaa=rs1.getString("place1");
String bbb=rs1.getString("place2");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
DispDay dc=new DispDay();
}
ps1.close();
rs1.close();
conn1.close();
}
else
{
System.out.print("N");
System.out.println("Sorry!!!");
}
}
ps.close();
rs.close();
conn.close();
Trace your code to see where you're getting the data. The error is on this line:
String aaa=rs1.getString("place1");
Where does rs1 come from?:
ResultSet rs1 = ps.executeQuery();
Where does ps come from?:
PreparedStatement ps = conn.prepareStatement(sql);
Where does sql come from?:
String sql ="Select Day from menu where ID =?";
There's no column being selected called place1. This query is only selecting a single column called Day.
Maybe you meant to get the result from the second prepared statement?:
ResultSet rs1 = ps1.executeQuery();
There are probably more such errors. Perhaps several (or many) more. Because...
Hint: Using meaningful variable names will make your code a lot easier to follow. ps, ps1, rs1, etc. are very easy to confuse. Name variables by the things they conceptually represent and your code starts to read like a story which can be followed. Variable names like daysQuery and daysResults and placesResults make it more obvious that something is wrong when you try to find a "place" in a variable which represents "days".
In your second query:
PreparedStatement ps1 = conn.prepareStatement(sql);
you are accidentally using the variable sql instead of your previously defined sql1. Replace it and it will be ok.

Fetch a column into the result set which is not in the table

My Title might not be clear enough. So let me explain the problem . I have to retrieve the values from the database store it in an array list and display it in a jsp page dynamically. for that am using a query
select customer,
id,
0 message
from TableName
My Table Structure:
customer varchar2(20)
id Number
I don't know how to add the column 0 message into the result set since this column is not present in that table.
For example, if we give
select 0 message
from TableName;
The output of the above query will be
message
0
So now my question is how to add this column(message) into my Resultset and Array list?
When you add it to your SQL-query as in your question it should also appear in the resultset...
Just wondering if you are facing any issue with executing the SQL query with the additional (non-existing in DB) column through JDBC.
for eg: - you can execute the below query directly in the database through JDBC
select customer,
id,
0 "message"
from TableName
Sample Code snippet.
Connection conn = DriverManager.getConnection(".....", "...","..");
ps = conn.prepareStatement("select customer, id, 0 \"message\" from your_table");
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.printf("%s %s %s", rs.getString("id"), rs.getString("customer"), rs.getString("message"));
}
Hlo.. below code will help you..
package com.smk.jdbc.ps;
import java.util.ArrayList;
public class PreparedStatement {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.OracleDriver");
java.sql.Connection conn = null;
java.sql.PreparedStatement ps = null;
String strQry = "select 1 message from dual where 1 = ?";
conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:#localhost:wzdev", "user","pwd");
ps = conn.prepareStatement(strQry);
ps.setInt(1, 1);
java.sql.ResultSet rs = ps.executeQuery();
while(rs.next()){
java.util.ArrayList<java.sql.ResultSet> ars = new ArrayList<java.sql.ResultSet>();
ars.add(rs);
System.out.println(ars.get(0).getInt("message"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
This code is working fine for sql server.And doing same for whatever u want.
public class ConnectionPool
{
public static void main(String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("","","");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select sRowId, 0 messa from tblAccount");
while(rs.next())
{
list.add(rs.getInt("messa"));
}
System.out.println(list.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

How to define a Label class in MyEclipse?

I have set many lables and I want them to show the data from database.But it shows"com.myql.jdbc.JDBC4ResultSet"
The sql sentences' results are double
And there is the code as follows
private void initData() {
initCondition("select sum(initAmount) from account", lblInit);
initCondition("select sum(amount) from detail where directionid = 1", lblIncome);
initCondition("select sum(amount) from detail where directionid = 2", lblOutcome);
lblAsset.setText("as");
}
//It's my definition about the label class.
private void initCondition(String sql, JLabel jLabel) {
try {
Connection connection = DriverManager.getConnection(url, user,
password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
jLabel.setText(resultSet.toString());
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
// TODO: handle exception
}
The result of sql is a double number. I think the resultset needn't loop.
Are you saying the result set contains just one column of data in one row? In that case, maybe something along the lines of..
ResultSet resultSet = statement.executeQuery(sql);
resultSet.first();
jLabel.setText("" + resultSet.getDouble(1));

Categories