package myproj;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import myproj.util.DBUtil;
/**
*
* #author PEARL
*/
public class DATAENTRY extends javax.swing.JFrame {
/**
* Creates new form DATAENTRY
*/
public DATAENTRY() {
try {
initComponents();
DBUtil util = new DBUtil();
Connection con = util.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from bk_det inner join bk_rep on bk_det.rm_id = bk_rep.rm_id inner join bk_sec on bk_rep.rm_id = bk_sec.rm_id inner join mut_det on bk_sec.rm_id = mut_det.rm_id inner join rm_det on mut_det.rm_id = rm_det.rm_id inner join soil_det on rm_det.rm_id = soil_det.rm_id");
ResultSetMetaData rsmetadata = rs.getMetaData();
int columns = rsmetadata.getColumnCount();
DefaultTableModel dtm = new DefaultTableModel();
Vector columns_name = new Vector();
Vector data_rows = new Vector();
for(int i=1; i< columns; i++){
columns_name.addElement(rsmetadata.getColumnName(i));
}
dtm.setColumnIdentifiers(columns_name);
while(rs.next()){
data_rows = new Vector();
for(int j=1; j< columns; j++){
data_rows.addElement(rs.getString(j));
}
dtm.addRow(data_rows);
}
MyTable.setModel(dtm);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void main(String arg[]){
}
}
i want to display the records from my sql database to my jtable in netbeans gui but am able to display the compile and running the windows form successfully but it doesnot display the respected form please help
This is because you need to call DATAENTRY() in the main class
Your main method is empty, so it won't do anything.
public static void main(String arg[]){
}
Did you know that your main method is completely empty? Everything in your program happens from main. You would want to instantiate your DATAENTRY object from there.
DATAENTRY da = new DATAENTRY();
It may also be the case that other things break as well; be wary and conscious of any stack traces.
There's nothing in your main method. Java starts running code from the main method.
Add this
public static void main(String arg[]){
DATAENTRY de = new DATAENTRY() ;
de.pack();
de.setVisible(true)
}
Also class name DATAENTRY and all the stuff which you've done in constructor is not a proper standard. You should follow java code standards. Google it.
Class name can be like DataEntryFrame
call initialize component after constructing frame like deFrame.intilizeComponents()
put separate method for updating table content like fillupTable()
finally call fillupTable method with an event or in main method.
Related
how to solve this problem and what is wrong in this code?
i know that the question has been asked before but i cant solve the problem
private void cb_categoriesPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
cb_categories.removeAllItems();
try {
String sql_c = "SELECT * FROM inventory.categories";
cc.pst = cc.c.prepareStatement(sql_c);
cc.rs = cc.pst.executeQuery();
while (cc.rs.next()) {
String c_name = cc.rs.getString("CategoryName");
cb_categories.addItem(c_name);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
} finally {
try {
cc.rs.close();
cc.pst.close();
} catch (Exception e) {
}
}
}
Your ResultSet and PreparedStatement are not declared in method scope, so I have to assume that you've declared them elsewhere.
That's a big mistake.
You should declare the Statement and ResultSet in method scope.
You make an attempt to close your resources, but you should wrap them in individual try/catch blocks. You cannot risk one being closed and not the other.
There are other things I'd criticize about your code (e.g. SELECT *, mingling UI and database code together in a single class), but that's enough to start.
Start with an interface:
package persistence;
import java.util.List;
/**
* Created by Michael
* Creation date 8/20/2017.
* #link https://stackoverflow.com/questions/45787151/com-mysql-jdbc-exception-jdbc4-mysqlnontransientconnectionexception-no-operatio/45787321?noredirect=1#comment78532554_45787321
*/
public interface CategoryDao {
List<String> findAllCategories();
}
Then write a concrete implementation:
package database;
import database.util.DatabaseUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Michael
* Creation date 8/20/2017.
* #link https://stackoverflow.com/questions/45787151/com-mysql-jdbc-exception-jdbc4-mysqlnontransientconnectionexception-no-operatio/45787321?noredirect=1#comment78532554_45787321
*/
public class CategoryDaoImpl implements CategoryDao {
private static final Log LOGGER = LogFactory.getLog(CategoryDaoImpl.class);
private static String SELECT_CATEGORIES = "SELECT CategoryName from inventory.Categories ";
private DataSource dataSource;
public CategoryDaoImpl(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<String> findAllCategories() {
List<String> categories = new ArrayList<>();
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = this.dataSource.getConnection().prepareStatement(SELECT_CATEGORIES);
rs = ps.executeQuery();
while (rs.next()) {
categories.add(rs.getString("CategoryName"));
}
} catch (SQLException e) {
LOGGER.error(String.format("Exception caught while selecting all category names"), e);
} finally {
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return categories;
}
}
This is something that you can test with JUnit off to the side. Get it running perfectly, then give a reference to your UI code. It'll keep the UI and database code separate. You can use this DAO in any application without worrying about Swing or web UI.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm trying to use JFileChooser to get the directory of a database file for my inventory control software.
The problem is that JFileChooser only gets the directory of the file after the file explorer is displayed twice and the file is chosen twice.
The code is below:
package groupassignment;
import java.io.File;
import java.sql.Connection;
import java.sql.*;
import java.sql.SQLException;
import javax.swing.*;
/**
*
* #author ashraf141298
*/
public class GetDatabase {
static Connection con;
static Statement st;
static ResultSet rs;
public GetDatabase() {
connect();
}
public String getFileDirectory() {
JFileChooser filechooser = new JFileChooser();
File db = null;
String directory;
if(filechooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
db = filechooser.getSelectedFile();
System.out.println("Opening file: " + db);
} else {
System.out.println("No file was chosen or an error occured");
System.exit(0);
};
directory = db.toString();
return directory;
}
public void connect() {
try{
String dbURL = "jdbc:ucanaccess://" + getFileDirectory();
// Attempt to connect to the database
con = DriverManager.getConnection(dbURL);
// Extract data from the table using SQL sta
st = con.createStatement();
String query = "select * from ProductBarcodes";
rs = st.executeQuery(query);
} catch(SQLException e){
JOptionPane.showMessageDialog(null, "Unable to connect to database", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
}
public static void main(String[] args) {
GetDatabase database = new GetDatabase();
DisplayDatabase gui = new DisplayDatabase();
}
}
Code for DisplayDatabase:
package groupassignment;
import static groupassignment.GetDatabase.rs;
import javax.swing.*;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.table.DefaultTableModel;
/**
*
* #author ashraf141298
*/
public class DisplayDatabase extends GetDatabase {
public DisplayDatabase() {
display();
}
public void display() {
// It creates and displays the table
JTable table = null;
try {
table = new JTable(buildTableModel(rs));
} catch (SQLException ex) {
System.out.println("Unable to create JTable");
}
// Closes the Connection
JOptionPane.showMessageDialog(null, new JScrollPane(table), "Current Stocklist", JOptionPane.INFORMATION_MESSAGE);
}
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// get the names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// get the data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
// return the database in TableModel form
return new DefaultTableModel(data, columnNames);
}
}
you have extends DisplayDatabase with GetDatabase class
DisplayDatabase extends GetDatabase{
...
}
so when you create a new instance of GetDatabase class constructor of super class [GetDatabase] get invoked and connect method get called again.
so you get another jfilechooser popup window.
GetDatabase database = new GetDatabase();
so how to fix
if you don't want to inherit anything from GetDatabase class you can remove extends part.
but if you want to inherit from GetDatabase class then,
instead of connect db from constructor , you can do it from a method.
public GetDatabase() {
// connect();// not here
}
public void ConnectDatabase(){
connect();
}
so you call this method .
public static void main(String[] args) {
GetDatabase database = new GetDatabase();
database.ConnectDatabase();
DisplayDatabase gui = new DisplayDatabase();
}
May be the function is being triggered more than once, your code for calling file chooser seems to work fine.
I'm trying to retrieve data from a database and use the ResultSet , but I don't get the desired output
Main program:
import java.sql.ResultSet;
import java.sql.SQLException;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class classname_main{
public static void main(String[] args) throws SQLException{
classname abc=new classname();
ResultSet asdf= (ResultSet) abc.runconnect();
abc.printdata();
}
}
Class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
public class classname{
public static Object runconnect(){
try{
//get connection
Connection connection = DriverManager.getConnection("");
//Create Statement
Statement st = connection.createStatement();
//ex query
//Resultset
ResultSet rs = st.executeQuery("");
float time=9;
while(rs.next())
{
if(time<20){
String x=(rs.getString(9));
Float y=(rs.getFloat(5));
//System.out.println(rs.getString(""));
time=time+duration;
//System.out.println(x);
if(x>=20){
x=9;
}
}
}
return rs;
}
catch(Exception ex){
ex.printStackTrace();
}
return 0;
}
public static Object printdata(){
classname pd = new classname();
ResultSet drs = (ResultSet) pd.runconnect();
System.out.println(drs);
return null;
}
}
Output:
com.mysql.jdbc.JDBC42ResultSet#5910e440
Try to use .getString(...) or .getInt(...) ...to retrieve desired values like this ex:
System.out.println(drs.getString(some value));
Instead of: System.out.println(drs);
I am working on a dictionary project in Java on Netbeans. I have two classes here:
"dictionary.java" where the main method is
"DictionaryGuiController.java" where GUI code is constructed with javafx platform
I connected the database and project with JDBC driver and using these codes in main method:
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/world", "root", "root");
statement = conn.createStatement();
rs = statement.executeQuery("SELECT * FROM country");
while (rs.next()) {
System.out.println(rs.getString("code") + ":" + rs.getString("name"));
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
Here I created a connection object as conn to create statements and executing the SQL query.
I want to retrieve data from a sample database in Mysql called "world". With this code I am able to retrieve data in a small project that has only one class and main method. But in this project when I run the program I see the GUI interface but I can not see any results in the console, it keeps saying:
Executing C:\Users\Bar\Documents\NetBeansProjects\Dictionary\dist\run414351490\Dictionary.jar using platform C:\Program Files\Java\jdk1.7.0_45\jre/bin/java
and program never stops until program exits.
Here is the complete code of the classes:
Dictionary.java:
package dictionary;
import java.io.IOException;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.sql.*;
public class Dictionary extends Application {
#Override
public void start(Stage stage) throws IOException {
Parent root = FXMLLoader.load(getClass().getResource("DictionaryGui.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/world", "root", "root");
statement = conn.createStatement();
rs = statement.executeQuery("SELECT * FROM country");
while (rs.next()) {
System.out.println(rs.getString("code") + ":" + rs.getString("name"));
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
}
}
}
DictionaryGuiController.java:
package dictionary;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class DictionaryGuiController implements Initializable {
#FXML
private TextField searchfield;
#FXML
private Button buttonsearch;
#FXML
private TextArea listview;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
#FXML
private void handleButtonAction(ActionEvent event) {
listview.setText(searchfield.getText());
}
}
What could be the problem? Any help would be appreciated.
Two quick things that it could be. First, is your instance of MySQL already running? Secondly, I tend to do all my database connection stuff outside the main method. So I will have a method in the controller class called initDB() or connectToDB() and I put the code in there.
The convention I've seen for the main() method in JavaFX programs is that launch() is the only method called. I could be wrong, but check those two things and see if you have any luck.
import java.sql.*;
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.*;
import java.awt.*;
import javax.swing.table.*;
import java.util.Vector;
public class SimpleTable extends JFrame {
public SimpleTable() {
super("Simple JTable Test");
setSize(350, 200);
//setLocation(250,300);
int ColCount;
int i;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/employ_details","root","");
java.sql.Statement stmt= con.createStatement();
ResultSet rs= stmt.executeQuery("select * from employe_details ");
ResultSetMetaData meta =rs.getMetaData();
ColCount=meta.getColumnCount();
String s1 = null;
String s2 = null;
String s3 = null;
String s4 = null;
String s5 = null;
String s6 = null;
String s7 = null;
while (rs.next())
{
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rs.getString(i+1);
s1= rs.getString("Employee_ID");
s2= rs.getString("Employee_Name");
s3= rs.getString("Contact_Number");
s4 = rs.getString("Address");
s5 = rs.getString("Email");
s6 = rs.getString("dob");
s7 = rs.getString("Sex");
}
JTable jt = new JTable(new String[][]{{s1,s2,s3,s4,s5,s6,s7}}, new String[]{"Employee_ID","Employee_Name","Contact_Number","Address","Email","dob","Sex"});
JScrollPane jsp = new JScrollPane(jt);
getContentPane().add(jsp,BorderLayout.CENTER);
}}
catch (Exception e)
{
System.out.println("failure to connect " + e);
return; //(exit(1));
}
}
public static void main(String args[]) {
SimpleTable st = new SimpleTable();
st.setVisible(true);
}
}
its only shopwing the last row in the database .
how i get all the rows in the database to the JTable ?
Your code is reading all the data but it doesn't store all, it holds data of last loop execution only.
And creating table from last row so it will show last row only.
Try something like
List<String> data = new ArrayList<String>();
than
while (rs.next())
{
String [] record= new
String[ColCount];
for (i=0; i<ColCount; i++)
{
record[i]=rs.getString(i+1);
data.add(rs.getString("Employee_ID"));
data.add(rs.getString("Employee_Name"));
.
.
.
data.add(rs.getString("Sex"));
}
JTable jt = new JTable(new String[][]{data.toArray()}, new String[]{"Employee_ID","Employee_Name","Contact_Number","Address","Email","dob","Sex"});
You are iterating through the ResultSet and no storing all the values of returned by the ResultSet.
Your s1..s7, therefore, holds the last value from the resultset. You can either have s1[]..s7[] to hold all values, per column, from the resultset or have a List of all values in the set.
Best way, is to create a POJO object to map your entity (POJO) to your SQL table.
This is an easier problem if you break it into smaller steps.
Instead of putting all your code into one main method, I'd recommend breaking them into several smaller classes. Focus on one, get it working, then move onto the next thing.
Your first problem is data retrieval.
Java's an object-oriented language: start with an Employee class.
package model;
public class Employee
{
private String id;
private String name;
private String phone;
private String address;
private String email;
private Date birthday;
private Gender gender;
// Constructors, getters/setters, equals, hashCode, toString and behavior follow.
}
Once you have that written and tested, write a data access object to deal with the database:
package persistence;
public interface EmployeeDao
{
List<Employee> find();
Employee find(String id);
List<Employee findByName(String name);
void save(Employee e);
void update(Employee e);
void delete(Employee e);
}
Write an implementation for this and get it tested.
Only worry about the JTable when you've got these working. Your problems will be isolated to the UI at that point, because you've got the persistence sorted out.