In this tutorial you will learn to fetch the data from sql server database to jtable.
Code to fetch data from SQL Server database to JTable
For Fetching data from database and storing in Arraypublic ArrayList<User> userList(){
ArrayList<User> usersList = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databaseName=testdb;user=sa;password=orchid";
Connection con = DriverManager.getConnection(url);
String query1="SELECT * FROM users";
Statement st= con.createStatement();
ResultSet rs= st.executeQuery(query1);
User user;
while(rs.next()){
user=new User(rs.getInt("sno"), rs.getString("name"), rs.getString("address"), rs.getString("gender"), rs.getString("knowledge"), rs.getString("subject"));
usersList.add(user);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
return usersList;
}
//For showing in the columns of jtable
public void show_user(){
ArrayList<User> list = userList();
DefaultTableModel model = (DefaultTableModel)jTable_Display_User.getModel();
Object[] row = new Object[6];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getsno();
row[1]=list.get(i).getname();
row[2]=list.get(i).getaddress();
row[3]=list.get(i).getgender();
row[4]=list.get(i).getknowledge();
row[5]=list.get(i).getsubject();
model.addRow(row);
}
}
For Class Users
class User {private int sno;
private String name, address, gender, knowledge, subject;
public User(int sno, String name, String address, String gender, String knowledge, String subject)
{
this.sno=sno;
this.name=name;
this.address=address;
this.gender=gender;
this.knowledge=knowledge;
this.subject=subject;
}
public int getsno(){
return sno;
}
public String getname(){
return name;
}
public String getaddress(){
return address;
}
public String getgender(){
return gender;
}
public String getknowledge(){
return knowledge;
}
public String getsubject(){
return subject;
}
}
Please watch the video because there are some task to be done beside code
Youtube Channel Subscription Click Here
Please don't forget To Like, Share and Subscribe my Youtube video and Channel.
Thanks for the video and Tutorial Indra!! A question, when I put: ArrayList list = userList();
ReplyDeleteI get an error "cannot find symbol userList".
Any help with that?
while using this code i am getting stackoverflow error will you please help me with that?
ReplyDeleteGolden Nugget Casino in Las Vegas - MapyRO
ReplyDeleteGolden Nugget Casino - Golden Nugget Casino 김제 출장마사지 and 남원 출장샵 Hotel - 춘천 출장마사지 MapyRO 경주 출장안마 users and real-time reviews of Golden Nugget Casino, including real-time reviews 진주 출장샵 of