getting values in jtable upon seletio on jcombox - java

1.i have a jcombobox which is getting the value from database ,
2. upon the selection on the value i want to display that particular row in the jtable ,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Object obj = jComboBox1.getSelectedItem();
String tmpr = obj.toString();
Rtable rObj = new Rtable();
rObj.setUserName(tmpr);
}
private void Update_table(){
String Sql = "SELECT * FROM r_db1.dbo.user_names " + jComboBox1.getSelectedItem()
I am getting a error like "UnsupportedOperationException("Not supported yet.")"

Try this
use loadcombo() method to load ur jcombobox.
void loadcombo()
{
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
//userID = "Admin";
password = "***";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop","system","manager");
st=con.createStatement();
rs= st.executeQuery("select distinct(Name) from Table");
while(rs.next())
{
jComboBox.addItem(rs.getString(1));
}
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
use jcombobx actionlistener to load data into jtable.
jComboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";";
//sql = "SELECT * FROM tblUserProfile";
Object name=jComboBox.getSelectedItem();
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop","system","manager");
st=con.createStatement();
model.setRowCount(0);
data = getvalue(name);
JTable table1=new JTable(data,header);
for(int i=0;i<table1.getRowCount();i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};model.addRow(d);
}
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
public Vector getvalue(Object name)throws Exception
{
Vector<Vector<String>> vector = new Vector<Vector<String>>();
Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from Table where Name='"+name+"'");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> c = new Vector<String>();
c.add(rs.getString(4));
c.add(rs.getString(5));
c.add(rs.getString(6));
vector.add(c);
}
/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();
return vector;
}
});

Related

why doesn't it show in Jtable? i am trying to connect my database to my jtable

I can't see why this is broken I checked the url and user and password
here is my database properties
enter image description here
nothing wrong with the sql
enter image description here
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("oracle.jdbc.OracleDriver");
//conneting my database
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","system","sisidodo30");
Statement st = con.createStatement();
//the sql code
String sql = "SELECT * FROM \"SYSTEM\".STOCKSTABLEPROJECT";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
//for some reason it doesn't get in here
System.out.println("i am in the loop");
String Name = rs.getString("NAME");
String Price = String.valueOf(rs.getInt("PRICETODAY"));
String tbdata[] ={Name,Price};
DefaultTableModel tblModel =(DefaultTableModel)jTable1.getModel();
tblModel.addRow(tbdata);
}
con.close();
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}

Cannot populate jComboBox depending on other ComboBox from postgres

There are two ComboBoxes "jComboCins1 and jComboCinsM". I want to populate jComboCinsM depending on jComboCins1 from postgresql. Here is the code, no errors but still cannot populate. Thanks in advance for all replies.
public class MekleFrame extends javax.swing.JFrame {
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
Statement st = null;
/**
* Creates new form MekleFrame
*/
public MekleFrame() {
initComponents();
this.setLocationRelativeTo(null);
this.setResizable(false);
jTextFielddummy.setVisible(false);
conn = dbConnection.ConnectDB();
update_table();
pop_combo();
}
private void pop_combo(){
try {
//String cnsCo=jComboCins1.getSelectedItem().toString();
String sql = "SELECT * from cinsdb WHERE sinif= ?";
pst=conn.prepareStatement(sql);
//pst.setString(1,cnsCo);
pst.setString(1,String.valueOf(jComboCins1.getSelectedItem()));
rs=pst.executeQuery();
while (rs.next())
{
String cinsad = rs.getString("cinsad");
jComboCinsM.addItem(cinsad);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}

No suitable driver found for jdbc:mysql//localhost/sakila

I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

mysql Column not found loop

Hi have a method that creates a LinkedList of compMac object. CompMac object contain elements from a mysql table row. Each row contain a nickname and a location so I use a loop to create a 'compMac' for each row and add them in the linkedlist. I don't know why, but the first 'compMac' is created and is being added to the linkedlist, but after that I get
java.sql.SQLException: Column 'nickname' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1163)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5729)
at server.DbConnect.getArray(DbConnect.java:224)
at server.doComms.sendArray(doComms.java:127)
at server.doComms.whileChatting(doComms.java:107)
at server.doComms.run(doComms.java:32)
at java.lang.Thread.run(Thread.java:695)
Here is my method:
public LinkedList<compMac> getArray()
{
LinkedList<compMac> locArray = new LinkedList<compMac>();
try{
String query = "SELECT * FROM online";
rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
String loc = rs.getString("location");//mac addresses
String cX=getCoorX(loc);
String cY=getCoorY(loc);
String building=getBuilding(loc);
String floor=getFloor(loc);
locArray.add(new compMac(nn,loc,cX,cY,building,floor));
}
}
catch(Exception e){e.printStackTrace();}
return locArray;
}
But I do have a nickname column, I like I said, the first compMac is created, when I pop the linkedlist I get the first row's informations.
Thanks to anyone having an idea whats wrong with my code.
EDIT: Here the class code:
package server;
import java.sql.*;
import java.util.LinkedList;
import com.example.client.Mac;
import com.example.client.compMac;
public class DbConnect {
private Connection con;
private Statement st;
private Statement stClean;
private ResultSet rs;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://melucio.no-ip.biz:3306/TOC","XXXXX","XXXXXXX");
st = con.createStatement();
stClean = con.createStatement();
}catch(Exception ex){
System.out.println("Error: "+ex);
}
}
/*This method returns the x coor. of mac address*/
public String getCoorX(String mac){
String cX = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorX");
}
}
}
catch(Exception e){}
return cX;
}
/*This method returns the y coor. of mac address*/
public String getCoorY(String mac){
String cY = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorY");
}
}
}
catch(Exception e){}
return cY;
} public String getBuilding(String mac){
String buil = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("building");
}
}
}
catch(Exception e){}
return buil;
}
public String getFloor(String mac){
String fl = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("floor");
}
}
}
catch(Exception e){}
return fl;
}
/*Update the location table*/
public void updateLocation(String userNN,String location){//,long time){
long time = System.currentTimeMillis();
if(!isOnline(userNN))
{System.out.println("not online");
setOnline(userNN,location);}
else{
try{
//String query ="UPDATE online SET location = '" +location +"' WHERE nickname='" +userNN +"'";
String query ="UPDATE online SET location = '" +location +"', lastSeen = "+time +" WHERE nickname='" +userNN +"'";
st.executeUpdate(query);
}
catch(Exception e){System.out.println("ayayaya");}
}
}
public LinkedList<compMac> getArray()
{
LinkedList<compMac> locArray = new LinkedList<compMac>();
try{
String query = "SELECT * FROM online";
rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
String loc = rs.getString("location");//mac addresses
String cX=getCoorX(loc);
String cY=getCoorY(loc);
String building=getBuilding(loc);
String floor=getFloor(loc);
locArray.add(new compMac(nn,loc,cX,cY,building,floor));
}
}
catch(Exception e){e.printStackTrace();}
return locArray;
}
public void clean()
{
long currentTime = System.currentTimeMillis();
long acceptableTime = currentTime-120000;
try{
String query = "SELECT * FROM online";
rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
Long ls = rs.getLong("lastSeen");
if(ls<acceptableTime)//{}
{stClean.executeUpdate("DELETE FROM online WHERE nickname='"+nn+"'");}
}
}
catch(Exception e){e.printStackTrace();}
}
}
As per your code you are reusing the same Statement object in different methods. So after the first iteration the last method getFloor changes the st object to query on coordinate table. I suggest you initialize separate Statement objects in every method and close it in finally block.
import com.example.client.Mac;
import com.example.client.compMac;
public class DbConnect {
private Connection con;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://melucio.no-ip.biz:3306/TOC","XXXXX","XXXXXXX");
}catch(Exception ex){
System.out.println("Error: "+ex);
}
}
/*This method returns the x coor. of mac address*/
public String getCoorX(String mac){
String cX = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorX");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return cX;
}
/*This method returns the y coor. of mac address*/
public String getCoorY(String mac){
String cY = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorY");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return cY;
} public String getBuilding(String mac){
String buil = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("building");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return buil;
}
public String getFloor(String mac){
String fl = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("floor");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return fl;
}
/*Update the location table*/
public void updateLocation(String userNN,String location){//,long time){
long time = System.currentTimeMillis();
if(!isOnline(userNN))
{System.out.println("not online");
setOnline(userNN,location);}
else{
try{
//String query ="UPDATE online SET location = '" +location +"' WHERE nickname='" +userNN +"'";
String query ="UPDATE online SET location = '" +location +"', lastSeen = "+time +" WHERE nickname='" +userNN +"'";
st.executeUpdate(query);
}
catch(Exception e){System.out.println("ayayaya");}
}
}
public LinkedList<compMac> getArray()
{
LinkedList<compMac> locArray = new LinkedList<compMac>();
try{
String query = "SELECT * FROM online";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
String loc = rs.getString("location");//mac addresses
String cX=getCoorX(loc);
String cY=getCoorY(loc);
String building=getBuilding(loc);
String floor=getFloor(loc);
locArray.add(new compMac(nn,loc,cX,cY,building,floor));
}
rs.close();
st.close();
}
catch(Exception e){e.printStackTrace();}
return locArray;
}
public void clean()
{
long currentTime = System.currentTimeMillis();
long acceptableTime = currentTime-120000;
try{
String query = "SELECT * FROM online";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
Long ls = rs.getLong("lastSeen");
if(ls<acceptableTime)//{}
{stClean.executeUpdate("DELETE FROM online WHERE nickname='"+nn+"'");}
}
}
catch(Exception e){e.printStackTrace();}
}

Categories