No output in Jtable from SQL. Java - java

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));

Related

java.sql.SQLException: Column 'Max(category_id' not found

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

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);
}
}

NullPointerException error in login by JDBC query

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?

USER defined java class step in pentaho data integration

Hi,
I am using the below code in USER DEFINED JAVA CLASS:
//STEP 1. Import required packages import java.sql.*;
import org.pentaho.di.core.database.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL ="jdbc:mysql://localhost:1111/mysql";
// Database credentials
static final String USER = "USER";
static final String PASS = "PASS";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null; try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "select id,sorname,src_databasetype,src_databasename from table";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
String sorname = rs.getString("sorname");
String src_databasetype = rs.getString("src_databasetype");
String src_databasename = rs.getString("src_databasename");
//Display values
System.out.print("ID: " + id);
System.out.print(", sorname: " + sorname);
System.out.print(", src_databasetype: " + src_databasetype);
System.out.println(", src_databasename: " + src_databasename);
}
rs.close(); }catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace(); }catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace(); }finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample
Running the code through command prompt its working fine
BUT on running the step(In PDI) alone I am getting error:
Non-abstract class "Processor" must implement method "boolean org.pentaho.di.trans.steps.userdefinedjavaclass.TransformClassBase.processRow(org.pentaho.di.trans.step.StepMetaInterface,
org.pentaho.di.trans.step.StepDataInterface) throws
org.pentaho.di.core.exception.KettleException"
For UDJC, I think instead of putting code in the main method, you need to put it in processRow().
Instead of using -
public static void main(String[] args)
use -
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
I am still skeptical if its still going to work as I don't understand what you're trying to do with that code.
Try writing your code in processRow method as follows:
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException{
Object[] r = getRow();
if (r == null) {
setOutputDone();
return false;
}
Object[] outputRow = createOutputRow(r, data.outputRowMeta.size());
//String row = getString(r)+",";
//setValue(outputRow, row)
putRow(data.outputRowMeta, outputRow);
return true;
}

How to get value at particular index from a vector?

When I return vector data using elementAt(2), I am getting this output.
Hello [162, Experiment 3.doc, E:\Desktop\Experiment 3.doc, doc, 35.5 kb]
I want the index value: "Experiment 3.doc".
// Function to fetch data from Database and store in jtable
public Vector getEmployee(String searchQuery)throws Exception
{
Connection con = null;
try{
Class.forName(driver);
} catch(java.lang.ClassNotFoundException e) {
e.printStackTrace();
}
try{
Vector<Vector<String>> employeeVector = new Vector<>();
con = DriverManager.getConnection(url,"conjure","conjure");
String query = "SELECT * FROM APP.FILES WHERE NAME LIKE '%"+searchQuery+"%'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
Vector<String> file = new Vector<>();
file.add(rs.getString(1)); //Empid
file.add(rs.getString(2)); //name
file.add(rs.getString(3)); //position
file.add(rs.getString(4)); //externsion
file.add(rs.getString(5)); //size
employeeVector.add(file);
}
rs.close();
return employeeVector;
} catch (Throwable err) {
err.printStackTrace();
System.out.println("Inside two");
} finally {
con.close();
}
return null;
}
// Button click, show data in jtable.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
String searchQuery = jTextField1.getText();
//get data from database
DBEngine dbengine = new DBEngine();
try {
data = dbengine.getEmployee(searchQuery);
System.out.println("Hello "+data.elementAt(2));
jTable1.setModel(new DefaultTableModel(data,header));
} catch (Exception ex) {
ex.printStackTrace();
}
}
Now I want to use column 3, i.e. filename (Experiment 3.doc) somewhere else.
How can I do that?
You have a Vector of Vectors.
data.elementAt(2) will return a Vector of Strings. You then need to get the next element from this resulting Vector, presumably data.elementAt(2).getElementAt(2)

Categories