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);
}
}
}
Related
Here is my code. It gives me an exception error says "java.sql.SQLException: Column 'Max(category_id' not found.". Please help. Thanks in advance.
enter code here
public class Category extends javax.swing.JFrame {
/**
* Creates new form Category
*/
public Category() {
initComponents();
DisplayTable();
autoID();
}
//Display Table
private void DisplayTable() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
String sql = "SELECT * FROM category";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public void autoID() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT Max(category_id) from category");
rs.next();
rs.getString("Max(category_id)");
if(rs.getString("Max(category_id") == null) {
CategoryIDField.setText("C0001");
}
else {
Long id = Long.parseLong(rs.getString("Max(category_id").substring(2, rs.getString("Max(category_id").length()));
id++;
CategoryIDField.setText("C0" + String.format("%03d", id ));
}
}
catch(ClassNotFoundException e) {
Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
}
catch(SQLException e) {
Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
}
}
The column has a default name but it isn't the same as the function, the easiest option would be to change all
rs.getString("Max(category_id)");
to
rs.getString(1);
Alternatively, name the column in your query. Like,
ResultSet rs = s.executeQuery("SELECT Max(category_id) AS FRED from category");
then use
rs.getString("FRED");
for example. Finally, you should be using getInt or getLong if the column is of those types (which I suspect because you are taking the MAX).
I think in the line
if(rs.getString("Max(category_id") == null) {
CategoryIDField.setText("C0001")
the quote should be after the round bracket.
use alisa
select Max(category_id) as xxx from category
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);
}
}
I am working with a java, SQL, swing JFrame project. I am new to programming and I've been trying to solve this problem for hours without any success.
The program I am trying to create is supposed to connect to my database (which is working) and then display the data from SQL database into a jtable - which is not working 100%.
Right now, the only thing that prints on the Jtable are the number "0". If I create a "Sout" the right info is printed in the normal NetBeans output.
I don't get an error, so the problem is quite complex. Thanks for your time=)
My first thread here! Sorry for the mess.
THE PROBLEM: I don't get the correct output from my database to my Jtable. The right output should be USER related output e.g Name, telephone number - Not "0 0 0"
DATABASE
public ArrayList<Kund> kundlista()throws ClassNotFoundException,
SQLException{
ArrayList<Kund> kundlista11 = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
System.out.println("Connecting to database...");
conn2 = DriverManager.getConnection("jdbc:sqlserver://milledb.database.windows.net:1433;database=Javamille;user=mille#milledb;password={Jagheter12};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
stmt2 = conn2.createStatement();
String sql2;
sql2 = "SELECT * FROM Kund";
ResultSet rs2 = stmt2.executeQuery(sql2);
Kund kund;
//STEP 5: Extract data from result set
while(rs2.next()){
int Kund_TeleNr = rs2.getInt("Kund_TeleNr");
int Kund_Pnr = rs2.getInt("Kund_Pnr");
String Kund_Fnamn = rs2.getString("Kund_Fnamn");
String Kund_Enamn = rs2.getString("Kund_Enamn");
System.out.print("Kundens telenr: " + Kund_TeleNr);
System.out.println("Kundens efternamn: " + Kund_Pnr);
kund=new Kund(rs2.getInt("Kund_Telenr"), rs2.getInt("Kund_Pnr"), rs2.getString("Kund_Fnamn"), rs2.getString("Kund_Enamn") );
kundlista11.add(kund);
}
//STEP 6: Clean-up environment
rs2.close();
stmt2.close();
conn2.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
return kundlista11;
}
}
SWING/UI class
public class KundUI extends javax.swing.JFrame {
/**
* Creates new form KundUI
*/
public KundUI() {
initComponents();
}
public ArrayList<Kund> lista;
public ArrayList<Kund> kundlista() throws ClassNotFoundException{
ArrayList<Kund> kundlistan = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn2 = null;
Statement stmt2 = null;
System.out.println("123.");
System.out.println("Connecting..");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn2 =
DriverManager.getConnection("jdbc:sqlserver://milledb.database.windows.net:1433;database=Javamille;user=mille#milledb;password={Jagheter12};encrypt=true;trustServerCertificate=false;hostNameInCertificate=*.database.windows.net;loginTimeout=30;");
//STEP 4: Execute a query
System.out.println("Hämtar kunder...");
stmt2 = conn2.createStatement();
String sql2;
sql2 = "SELECT * FROM Kund";
ResultSet rs2 = stmt2.executeQuery(sql2);
Kund kund;
//STEP 5: Extract data from result set
while(rs2.next()){
//Retrieve by column name
int Kund_TeleNr = rs2.getInt("Kund_TeleNr");
int Kund_Pnr = rs2.getInt("Kund_Pnr");
String Kund_Fnamn = rs2.getString("Kund_Fnamn");
String Kund_Enamn = rs2.getString("Kund_Enamn");
System.out.print("Kundens telenr: " + Kund_TeleNr);
System.out.print("Kundens förfanmn: " + Kund_Fnamn);
System.out.println("Kundens efternamn: " + Kund_Enamn);
System.out.println("Kundens efternamn: " + Kund_Pnr);
kund=new Kund(rs2.getInt("Kund_Telenr"), rs2.getInt("Kund_Pnr"), rs2.getString("Kund_Fnamn"), rs2.getString("Kund_Enamn") );
kundlistan.add(kund);
}
//STEP 6: Clean-up environment
rs2.close();
stmt2.close();
conn2.close();
}catch(SQLException e){
//Handle errors for JDBC
JOptionPane.showMessageDialog(null, e);
}
return kundlistan;
}
public void visa_kunder() throws ClassNotFoundException{
DefaultTableModel model = (DefaultTableModel)KundInfoUI.getModel();
Object[] row = new Object[4];
for(int i=0;i<lista.size();i++){
row[0]=lista.get(i).getTelenr();
row[1]=lista.get(i).getPnr();
row[2]=lista.get(i).getFnamn();
row[3]=lista.get(i).getEnamn();
model.addRow(row);
}
}
MAIN
package javaprojekt;
import java.sql.SQLException;
import java.util.ArrayList;
public class JavaProjekt {
public static void main(String[] args) throws ClassNotFoundException,
SQLException {
Databas data = new Databas();
BabbeJonas loginGui = new BabbeJonas();
loginGui.setVisible(true);
KundUI kundUiT = new KundUI();
while (loginGui.password1234 == false){
System.out.println("Hej");
}
if(data.login(loginGui.getUserName(), loginGui.getPassWord()) !=
true){
// databasen hämtar kunder
ArrayList<Kund> kundlist; // Lista som finns i MAIN
kundUiT.lista= (ArrayList<Kund>)data.kundlista().clone();
kundUiT.setVisible(true);
for(int i = 0; i < kundUiT.lista.size(); i++) {
System.out.println(kundUiT.lista.get(i).getPnr());
}
while(true){
}
}
}
}
you can fill your table with this line of code:
KundInfoUI.setModel(DbUtils.resultSetToTableModel(rs2));
The below code always generates a NullPointerException error.
The connection:
Connection con;
java.sql.PreparedStatement st;
public void Connect()
{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String user = "root";
String password = "";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mpdb",user,password);
String sql = new String("SELECT * FROM 'dati' WHERE user =? and pass =?");
st = con.prepareStatement(sql);
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Connessione non riuscita");
ex.printStackTrace();
}
}
The login:
#SuppressWarnings("deprecation")
public void mouseClicked(MouseEvent arg0) {
TextFields tf = new TextFields();
Driver d = new Driver();
try{
String sql = new String("SELECT user,pass FROM 'dati' WHERE user =? and pass =?");
ps = d.con.prepareStatement(sql);
ps.setString(1,tf.ftf.getText()); //JFormattedTextField
ps.setString(2,tf.pf.getText()); //JPasswordField
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "User successfully logged");
}else{
JOptionPane.showMessageDialog(null, "User not found");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
The select statement is wrong. Single quotes (') denote string literals in SQL, not object names (in your case - the table name). Since the SQL is invalid, no result set can be created, and hence the exception.
To resolve this, you should remove the quotes around 'dati':
String sql = "SELECT user,pass FROM dati WHERE user =? and pass =?"
I resolved with this code:
Execute connection:
package main;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class Driver {
Connection con = null;
public static Connection Join()
{
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String user = "root";
String password = "";
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mpdb",user,password);
return con;
}catch(Exception ex){
JOptionPane.showMessageDialog(null, "Connessione non riuscita");
ex.printStackTrace();
return null;
}
}
}
Login Button:
#SuppressWarnings("deprecation")
public void mouseClicked(MouseEvent arg0) {
TextFields tf = new TextFields();
String sql = new String("SELECT * FROM `dati` WHERE user = ? and pass = ?");
try{
ps = con.prepareStatement(sql);
ps.setString(1,tf.ftf.getText().trim());
ps.setString(2,tf.pf.getText().trim());
rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Login effettuato");
}else{
JOptionPane.showMessageDialog(null, "Utente o password non corretti");
}
}catch(Exception ex){
ex.printStackTrace();
}
}
public void mousePressed(MouseEvent arg0) {
}
public void mouseReleased(MouseEvent arg0) {
}
});
But now I've a new problem: the program do its work but it doesn't compare correctly the password. How do I have to proceed?
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;
}
});