hi everyone i have this code but don't know why it doesn't work!
//in database class
String query = "SELECT group_name FROM customer ORDER BY group_name";
java.sql.PreparedStatement stm = connection.prepareStatement(query);
rs = stm.executeQuery(query);
while (rs.next()) {
String x = rs.getString("group_name");
System.out.println(x);
}
rs.close();
}
//combo box action
int group = jcombobox.getSelectedIndex();
rg_domain rg = new rg_domain();
rg.setGroup(group);
rg.setPhone_number(phone_no);
dbconnection db = new dbconnection();
db.broadcastmsgservice_sms(rg);
}
//domain class
private String group;
public void setGroup(String group) {
this.group = group;
}
public String getGroup() {
return group;
}
can anyone help me please..
Your question is not very clear, but here's how you fill a combo box with results retrieved from the database:
// Create an array list to be filled with group names
ArrayList<String> groupNames = new ArrayList<String>();
String query = "SELECT group_name FROM customer ORDER BY group_name";
PreparedStatement stm = connection.prepareStatement(query);
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
String groupName = rs.getString("group_name");
// add group names to the array list
groupNames.add(groupName)
}
rs.close();
// Populate the combo box
DefaultComboBoxModel model = new DefaultComboBoxModel(groupNames.toArray());
comboBox.setModel(model);
Related
there is table of employee in database like in this image and use jdbc and java to fetch data from table. expected result also in image.
desired output in image
You can create an Employee class which contains the list of reports as below along with empId and reportingId:
public class Employee {
private String empId;
private String reportingId;
private List<Employee> reports;
public Employee(String empId, String reportingId) {
this.empId = empId;
this.reportingId = reportingId;
this.reports = new ArrayList<>();
}
public String getEmpId() {
return empId;
}
public String getReportingId() {
return reportingId;
}
public List<Employee> getReports() {
return reports;
}
}
// Step 1: Connect to the database
Connection conn = DriverManager.getConnection(connectionString, username, password);
// Step 2: Execute a SELECT statement
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT empId, reportingId FROM employee");
// Step 3: Iterate over the resultset and create a Map of Employee objects
Map<String, Employee> employees = new HashMap<>();
while (rs.next()) {
String empId = rs.getString("empId");
String reportingId = rs.getString("reportingId");
Employee employee = new Employee(empId, reportingId);
employees.put(empId, employee);
}
// Step 4: Iterate over the Map and create the hierarchy of Employee objects
for (Employee employee : employees.values()) {
Employee manager = employees.get(employee.getReportingId());
if (manager != null) {
manager.getReports().add(employee);
}
}
// The hierarchy of Employee objects is now complete
You can then print the hierarchy of Employee objects using a recursive method, like this:
public void printHierarchy(Employee employee, int level) {
for (int i = 0; i < level; i++) {
System.out.print("\t");
}
System.out.println(employee.getEmpId());
for (Employee report : employee.getReports()) {
printHierarchy(report, level + 1);
}
}
Call the printHierarchy method from 101 employee
Output:
101
1013
1012
101222
101223
1011
101101
101102
I have a small question to you guys.
I tryed to add user to database.
User have field like: id, name, surname etc.
Method
public static String insertUsertoDatabase(Connection con, User userToAdd)
doing something like this
// the mysql insert statement
String query = " insert into User (id,log,pass)"
+ " values (?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, 1);
preparedStmt.setString(2, "h");
preparedStmt.setString(3, "l");
setUser method
public String setUser(User userToBase) {
return insertUsertoDatabase(con, userToBase);
}
and main.java
User us1 = new User("9", "h", "l");
db.setUser(us1); //insert to database User u1
How can I put values from User constructor to preparedStmt ?
I have a constructor like that:
public class User(id, login, pass) {
this.id = id;
etc.
}
but i want to know how can I send data from constructor
User us1 = new User("9", "h", "l");
to my method
public static String insertUsertoDatabase(Connection con, User userToAdd)
preparedStmt.setInt(1, 9); <------------- from User constructor
preparedStmt.setString(2, "h");
preparedStmt.setString(3, "l");
You probably need something like that:
// TODO: use meaningful names
private String pim;
private String pam;
private String poom;
public User(String pim, String pam, String poom) {
this.pim = pim;
this.pam = pam;
this.poom = poom;
}
public String getPim() {
return this.pim;
}
// ...
Then:
User usr1 = new User("9", "h", "l");
usr1.getPim() // = "9"
// ...
Some reading on constructors
I have these codes
DBCollection.java
public LogInHandler userGreetName()
{
LogInHandler login = new LogInHandler();
String query = null;
try
{
query = "SELECT First_Name FROM user_information WHERE Username = '"+login.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
return login;
}
On my mainWindow.java I have formWindowOpened event and contains the codes
DBCollection dbc = new DBCollection();
greetNameL.setText(dbc.userGreetName().getGreetName());
LogInHandler.java
public class LogInHandler extends ValidateLogin{
DBCollection dbc = new DBCollection();
private String username;
private String greetName;
public void setGreetName(String temp)
{
greetName = temp;
}
public String getGreetName()
{
return greetName;
}
public void setUsername(String temp)
{
username = temp;
}
public String getUsername()
{
return username;
}
I have login.setUsername(usernameTF.getText()); in my loginWindowGUI
here's my problem.. I cant retrieve the First_Name column in my database.. it displays null. and is my WHERE condition in query is correct? help please..
Firstly, the way you've set your code exposes you to SQL injection.
query = "SELECT First_Name FROM user_information WHERE Username = '"+login.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
Something like the below should do the same job as your code, but protect you from SQL injection.
query = "SELECT First_Name FROM user_information WHERE Username = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setString(1, login.getUsername());
ResultSet rs = preparedStatement.executeQuery(query);
rs.next();
login.setGreetName(rs.getString("First_Name"));
I don't think that is what's causing your code not to work however. You need to give us more information.
Have you tried directly querying the DB with the following string?
SELECT First_Name FROM user_information WHERE Username = 'A user name that is definitely in the DB';
That should verify if your query is correct or not. If it works, then I would go into debug mode in Netbeans. Put a breakpoint before the following line
rs = stmt.executeQuery(query);
Check to see if login.username variable is populated. If that field is null, then your problem is there.
I am using following code for retrieving data from database, but i don't know how to show it in JList
Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt = null;
ResultSet rs;
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL","root","PWD");
stmt=(Statement) conn.createStatement();
rs=stmt.executeQuery(query);
while (rs.next())
{
String stadium = rs.getString("Stadium");
String city = rs.getString("City");
}
But i want to show column data in JList. Can you guys tell me how to do that?
i am using the following code but it is not displaying anything on my frame, can you please tell me where i am wrong? Thanks
String query="SELECT * FROM Location";
DefaultListModel model=new DefaultListModel();
DefaultListModel model1=new DefaultListModel();
try
{ Class.forName("oracle.jdbc.driver.OracleDriver");
Statement stmt = null;
ResultSet rs;
Connection conn=DriverManager.getConnection("jdbc:mysql://127.0.0.1/SPL","root","PWD");
stmt=(Statement) conn.createStatement();
rs=stmt.executeQuery(query);
while (rs.next())
{
String stadium = rs.getString("Stadium");
String city = rs.getString("City");
model.addElement(stadium);
model1.addElement(city);
}
JList list=new JList(model);
JList list1=new JList(model1);
f8.add(jpa1); //f8=frame name,jpa1=panel name
jpa1.add(list); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(1);
JScrollPane listScroller = new JScrollPane(list);
}
catch(SQLException e)
{
System.out.println("Message : " + e.getMessage());
}
A JList might be based on a ListModel, so you need to make a ListModel containing your data, and then use this to make your JList. I would make a class Stadium or something, with two String fields, name and city.
public class Stadium {
private String name;
private String city;
public Stadium(String name, String city){...}
//toString()-method to make it display in a meaningful way in the JList
public String toString(){ return name + " - " + city; }
}
and then you can write something like
...
DefaultListModel listModel = new DefaultListModel();
while (rs.next()) {
String name = rs.getString("Stadium");
String city = rs.getString("City");
Stadium stadium = new Stadium(name, city)
listModel.addElement(stadium);
}
JList list = new JList(listModel);
Have not tried to compile and test this code, but hopefully the point is helpful!
Hi while developing one of my web application i am storing the user information in to an ArrayList based on sql query executed, it contain duplicate objects how to remove duplicate objects in list , i already tried some method but it still not working.
This Is My Code Correct me where i am wrong
public ArrayList loadData() throws ClassNotFoundException, SQLException {
ArrayList userList = new ArrayList();
String url = "";
String dbName = "";
String userName = "";
String password = "";
Connection con = null;
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement ps = null;
try {
String name;
String fatherName;
int Id;
String filePath;
int age;
String address;
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
name = rs.getString(1);
fatherName = rs.getString(2);
age = rs.getInt(3);
address = rs.getString(4);
Id = rs.getInt(5);
filePath=rs.getString(6);
/* if(flag)
{
prev=Id;
flag=false;
}
else if(Id==prev)
{
TEMP=TEMP+";"+filePath;
}*/
//PhotoList = PhotoList(Id, con);
UserData list = new UserData();
list.setName(name);
list.setFatherName(fatherName);
list.setAge(age);
list.setAddress(address);
list.setId(Id);
// list.setFilePath(filePath);
userList.add(list);
}
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
ArrayList al = new ArrayList();
HashSet hs = new HashSet();
hs.addAll(userList);
al.clear();
al.addAll(hs);
return al;
}
And My Bean Class contant is
public class UserData {
private String name;
private String fatherName;
private int Id;
//private String filePath;
private int age;
private String address;
public UserData()
{
}
public UserData(String name, String fatherName,int Id, int age,String address)
{
this.name = name;
this.fatherName = fatherName;
this.Id = Id;
//this.filePath=filePath;
this.age=age;
this.address=address;
}
//GETTER AND SETTER..
General Idea: Use Set, not List. But you must override hash and equals of the class.
If you want a Collection of objects that does not have a specific order and you don't want duplicates, it's better for you just to use a Set like for example HashSet, or, if in your set the order is important, the TreeSet.
Just remember to override the hash and equals methods.
if you add this to your bean everything should work:
public int hashCode() {
return (name + fatherName+ Id + filePath + age + address).hashCode();
}
public boolean equals(Object obj) {
return ( hashCode() == obj.hashCode() );
}
Your userdata class does not implement equals or hashcode. This means two instances created with the same values will not be counted as duplicates. This is why the set contains duplicates.
For example
UserData u1 = new UserData("Foo", "bar",1, 1,"baz");
UserData u2 = new UserData("Foo", "bar",1, 1,"baz");
u1 and u2 are not considered equal as they are different objects. Adding an equals and hashcode method should fix this. However even better is adarshr's idea of removing dupes in the SQL.
All duplicates must be removed at an SQL level. Your SQL is suggesting that it could be generating duplicate records.
String query = "SELECT NAME,FATHERNAME,AGE,ADDRESS,ID,FILEPATH FROM USER_INFORMATION ,USER_PHOTO WHERE ID=USER_ID";
What does the clause ID = USER_ID mean? Shouldn't you be passing in that value as an input to your query?
Also, is the column ID a primary key? Otherwise, use a where clause that doesn't generate duplicates.