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.
Related
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I am new to java and started doing a javaFX project. In this project, I receive a variable from a previous frame, and use it to execute an SQL query in order to render the table based on that particular variable.
Here is my code:
package financials;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* #author param
*/
public class theControl implements Initializable {
#FXML
private Label test;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Statement st;
Connection con = null;
}
/**
*
* #param name
*/
public void previous(String name) {
System.out.println(name);
}
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "Password");
return con;
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
}
public static ObservableList<RenderNow> getListAccount() {
Connection con = ConnectDB();
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code=? ");
pst.setString(1, name); //This is where I am having trouble
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
}
The problem is that the variable name is not being recognized in the pst.setString line. The error I am getting is that variable 'name' is not found. I tried a different approach where I used name to set the text of Label test, and then later tried to get the variable in the public static Connection ConnectDB() method.
Something like:
public class theControl implements Initializable {
#FXML
private Label test;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Statement st;
Connection con = null;
}
/**
*
* #param name
*/
public void previous(String name) {
System.out.println(name);
test.setText(name); //Where i set the text of label 'text'
}
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "Password");
return con;
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
}
public static ObservableList<RenderNow> getListAccount() {
String name2 = test.getText(); //Where I try and get the text from label 'text'
Connection con = ConnectDB();
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code=? ");
pst.setString(1, name2); //This is where I am having trouble
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
}
However, this attempt returns an error non-static variable test cannot be referenced from a static context. My understanding is that since the label test is not static, static Connection is unable to get the text. Is there any work around for this ?
In your first case, the variable was not set. It's only available on the method where you have your print method.
In the second case, you are not using the object. The test variable is in one object, so not accessible by static method which are not depending of object.
I suggest you to ad new parameter to your static method, and use like this:
// create new static method which require the name in parameters
public static ObservableList<RenderNow> getListAccountWithName(String name) {
Connection con = ConnectDB(); // get DB thanks to static method
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code = '?'");
pst.setString(1, name); // now you can use name value
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
And now, you can call it from the object like:
ObservableList<RenderNow> accounts = getListAccountWithName(test.getText());
// now what you have what you are looking for
Closed. This question needs debugging details. It is not currently accepting answers.
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.
Closed 1 year ago.
Improve this question
package persistentie;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domein.Speler;
public class SpelerMapper {
private List<Speler> spelers = new ArrayList<>();
private List<Integer> scoreSpeler = new ArrayList<>();
private static final String UPDATE_SCORE = "insert into ID343589_g52.scoreSpeler(spelerNr,score) values(?,?)";
public SpelerMapper() {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement("SELECT * FROM ID343589_g52.speler");
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
String gebruikersnaam = rs.getString("gebruikersNaam");
String wachtwoord = rs.getString("wachtwoord");
spelers.add(new Speler(gebruikersnaam, wachtwoord));
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
public boolean correcteGegevens(Speler nieuweSpeler) {
return spelers.contains(nieuweSpeler);
}
public List<Integer> geefscoreSpeler(String naam) {
scoreSpeler.clear();
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
while (rs.next()) {
int score = rs.getInt("score");
scoreSpeler.add(score);
}
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
return scoreSpeler;
}
public void slaScoreOp(int score, String naam) {
try (Connection conn = DriverManager.getConnection(Connectie.JDBC_URL);
PreparedStatement query = conn.prepareStatement(String.format("SELECT sc.score FROM ID343589_g52.scoreSpeler sc join speler s on s.spelernr = sc.spelerNr where s.gebruikersNaam = '%s'", naam));
ResultSet rs = query.executeQuery()) {
int id = 0;
while (rs.next()) {
id = rs.getInt("score");
}
PreparedStatement update = conn.prepareStatement(UPDATE_SCORE);
update.setInt(1, id);
update.setInt(2, score);
update.executeUpdate();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
anything stupid I am doing here that is realy not how it working? I am really new to connecting a database with my java projects? the thing that I am trying to do in methode geefScoreSpeler() is getting the scores of an idividual player. and in methode slaScoreOp() I am trying to insert a new column in a table (also trying to get the id of the username via a table that innerjoins)
Hey there I made a user management system and this is my DAO(Databases connection class)
I have used prepared statement in this to see if it might help.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import com.ums.beans.ems.Employee;
public class EmployeeDao {
Connection connection;
Statement statement;
public EmployeeDao() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_1", "root", "apaar121");
}
public int saveEmployee(Employee employee) throws SQLException {
String query = "INSERT INTO user_1.employee ('name','dob','address','phone','email','education','designation','salary')VALUES (?,?,?,?,?,?,?,?);";
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,employee.getName());
preparedStatement.setString(2,employee.getAddress());
preparedStatement.setString(3,employee.getDesignation());
preparedStatement.setString(4,employee.getDob());
preparedStatement.setString(5,employee.getEducation());
preparedStatement.setString(6,employee.getEmail());
preparedStatement.setString(7,employee.getPhone());
preparedStatement.setFloat(8,employee.getSalary());
return preparedStatement.executeUpdate();
}
}
I came through a link: https://github.com/hyee/OpenCSV which drastically improves the writing time of the JDBC ResultSet to CSV due to setAsyncMode, RESULT_FETCH_SIZE
//Extract ResultSet to CSV file, auto-compress if the fileName extension is ".zip" or ".gz"
//Returns number of records extracted
public int ResultSet2CSV(final ResultSet rs, final String fileName, final String header, final boolean aync) throws Exception {
try (CSVWriter writer = new CSVWriter(fileName)) {
//Define fetch size(default as 30000 rows), higher to be faster performance but takes more memory
ResultSetHelperService.RESULT_FETCH_SIZE=10000;
//Define MAX extract rows, -1 means unlimited.
ResultSetHelperService.MAX_FETCH_ROWS=20000;
writer.setAsyncMode(aync);
int result = writer.writeAll(rs, true);
return result - 1;
}
}
But the problem is I don't know how I can merge above into my requirement. As the link has many other classes involved which I am not sure what they do and if I even need it for my requirement. Still, I tried but it fails to compile whenever I enable 2 commented line code. Below is my code.
Any help on how I can achieve this will be greatly appreciated.
package test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import com.opencsv.CSVWriter;
import com.opencsv.ResultSetHelperService;
public class OpenCSVTest1
{
static Connection con =null;
static Statement stmt = null;
static ResultSet rs = null;
public static void main(String args[]) throws Exception
{
connection ();
retrieveData(con);
}
private static void connection() throws Exception
{
try
{
Class.forName("<jdbcdriver>");
con = DriverManager.getConnection("jdbc:","<username>","<pass>");
System.out.println("Connection successful");
}
catch (Exception e)
{
System.out.println("Exception while establishing sql connection");
throw e;
}
}
private static void retrieveData(Connection con) throws Exception
{
try
{
stmt=con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
String query = "SELECT * FROM dbo.tablename";
rs=stmt.executeQuery(query);
CSVWriter writer = new CSVWriter(new BufferedWriter(new FileWriter("C:\\Data\\File1.csv")));
ResultSetHelperService service = new ResultSetHelperService();
/*** ResultSetHelperService.RESULT_FETCH_SIZE=10000; ***/ // to add
service.setDateTimeFormat("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println("**** Started writing Data to CSV **** " + new Date());
writer.setResultService(service);
/*** writer.setAsyncMode(aync); ***/ // to add
int lines = writer.writeAll(rs, true, true, false);
writer.flush();
writer.close();
System.out.println("** OpenCSV -Completed writing the resultSet at " + new Date() + " Number of lines written to the file " + lines);
}
catch (Exception e)
{
System.out.println("Exception while retrieving data" );
e.printStackTrace();
throw e;
}
finally
{
rs.close();
stmt.close();
con.close();
}
}
}
UPDATE
I have updated my code. Right now code is writing complete resultset in CSV at once using writeAll method which is resulting in time consumption.
Now what I want to do is write resultset to CSV in batches as resultset's first column will always have dynamically generated via SELECT query Auto Increment column (Sqno) with values as (1,2,3..) So not sure how I can read result sets first column and split it accoridngly to write in CSV. may be HashMap might help, so I have also added resultset-tohashmap conversion code if required.
import com.opencsv.CSVWriter;
import com.opencsv.ResultSetHelperService;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OpenCSVTest1
{
static int fetchlimit_src = 100;
static Connection con =null;
static Statement stmt = null;
static ResultSet rs = null;
static String filename = "C:\\Data\\filename.csv";
static CSVWriter writer;
public static void main(String args[])
{
try
{
connection();
retrieveData(con);
}
catch(Exception e)
{
System.out.println(e);
}
}
private static void connection() throws Exception
{
try
{
Class.forName("<jdbcdriver>");
con = DriverManager.getConnection("jdbc:","<username>","<pass>");
System.out.println("Connection successful");
}
catch (Exception e)
{
System.out.println("Exception while establishing sql connection");
throw e;
}
}
private static void retrieveData(Connection con) throws Exception
{
try
{
stmt=con.createStatement();
String query = "SELECT ROWNUM AS Sqno, * FROM dbo.tablename "; // Oracle
// String query = "SELECT ROW_NUMBER() OVER(ORDER BY Id ASC) AS Sqno, * FROM dbo.tablename "; // SQLServer
System.out.println(query);
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(fetchlimit_src);
System.out.println("**** Started querying src **** " + new Date());
rs=stmt.executeQuery(query);
System.out.println("**** Completing querying src **** " + new Date());
// resultset_List(rs); // If required store resultset(rs) to HashMap
writetoCSV(rs,filename);
/** How to write resultset to CSV in batches instead of writing all at once to speed up write performance ?
* Hint: resultset first column is Autoincrement [Sqno] (1,2,3...) which might help to split result in batches.
*
**/
}
catch (Exception e)
{
System.out.println("Exception while retrieving data" );
e.printStackTrace();
throw e;
}
finally
{
rs.close();
stmt.close();
con.close();
}
}
private static List<Map<String, Object>> resultset_List(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
while (rs.next())
{
Map<String, Object> row = new HashMap<String, Object>(columns);
for(int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
rows.add(row);
}
// System.out.println(rows.toString());
return rows;
}
private static void writetoCSV(ResultSet rs, String filename) throws Exception
{
try
{
writer = new CSVWriter(new BufferedWriter(new FileWriter(filename)));
ResultSetHelperService service = new ResultSetHelperService();
service.setDateTimeFormat("yyyy-MM-dd HH:mm:ss.SSS");
long batchlimit = 1000;
long Sqno = 1;
ResultSetMetaData rsmd = rs.getMetaData();
String columnname = rsmd.getColumnLabel(1); // To retrieve columns with labels (for example SELECT ROWNUM AS Sqno)
System.out.println("**** Started writing Data to CSV **** " + new Date());
writer.setResultService(service);
int lines = writer.writeAll(rs, true, true, false);
System.out.println("** OpenCSV -Completed writing the resultSet at " + new Date() + " Number of lines written to the file " + lines);
}
catch (Exception e)
{
System.out.println("Exception while writing data" );
e.printStackTrace();
throw e;
}
finally
{
writer.flush();
writer.close();
}
}
}
You should be able to use the OpenCSV sample, pretty much exactly as it is provided in the documentation. So, there should be no need for you to write any of your own batching logic.
I was able to write a 6 million record result set to a CSV file in about 10 seconds. To be clear -that was just the file-write time, not the DB data-fetch time - but I think that should be fast enough for your needs.
Here is your code, with adaptations for using OpenCSV based on its documented approach... But please see the warning at the end of my notes!
import com.opencsv.CSVWriter;
import com.opencsv.ResultSetHelperService;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.text.SimpleDateFormat;
public class OpenCSVDemo {
static int fetchlimit_src = 100;
static Connection con = null;
static Statement stmt = null;
static ResultSet rs = null;
static String filename = "C:\\Data\\filename.csv";
public static void main(String args[]) {
try {
connection();
retrieveData(con);
} catch (Exception e) {
System.out.println(e);
}
}
private static void connection() throws Exception {
try {
final String jdbcDriver = "YOURS GOES HERE";
final String dbUrl = "YOURS GOES HERE";
final String user = "YOURS GOES HERE";
final String pass = "YOURS GOES HERE";
Class.forName(jdbcDriver);
con = DriverManager.getConnection(dbUrl, user, pass);
System.out.println("Connection successful");
} catch (Exception e) {
System.out.println("Exception while establishing sql connection");
throw e;
}
}
private static void retrieveData(Connection con) throws Exception {
try {
stmt = con.createStatement();
String query = "select title_id, primary_title from imdb.title";
System.out.println(query);
stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
stmt.setFetchSize(fetchlimit_src);
System.out.println("**** Started querying src **** " + new Date());
rs = stmt.executeQuery(query);
System.out.println("**** Completing querying src **** " + new Date());
// resultset_List(rs); // If required store resultset(rs) to HashMap
System.out.println();
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
System.out.println("Started writing CSV: " + timeStamp);
writeToCsv(rs, filename, null, Boolean.FALSE);
timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
System.out.println("Finished writing CSV: " + timeStamp);
System.out.println();
} catch (Exception e) {
System.out.println("Exception while retrieving data");
e.printStackTrace();
throw e;
} finally {
rs.close();
stmt.close();
con.close();
}
}
public static int writeToCsv(final ResultSet rs, final String fileName,
final String header, final boolean aync) throws Exception {
try (CSVWriter writer = new CSVWriter(fileName)) {
//Define fetch size(default as 30000 rows), higher to be faster performance but takes more memory
ResultSetHelperService.RESULT_FETCH_SIZE = 1000;
//Define MAX extract rows, -1 means unlimited.
ResultSetHelperService.MAX_FETCH_ROWS = 2000;
writer.setAsyncMode(aync);
int result = writer.writeAll(rs, true);
return result - 1;
}
}
}
Points to note:
1) I used "async" set to false:
writeToCsv(rs, filename, null, Boolean.FALSE);
You may want to experiment with this and the other settings to see if they make any significant difference for you.
2) Regarding your comment "the link has many other classes involved": The OpenCSV library's entire JAR file needs to be included in your project, as does the related disruptor JAR:
opencsv.jar
disruptor-3.3.6.jar
To get the JAR files, go to the GitHub page, click on the green button, select the zip download, unzip the zip file, and look in the "OpenCSV-master\release" folder.
Add these two JARs to your project in the usual way (depends on how you build your project).
3) WARNING: This code runs OK when you use Oracle's Java 8 JDK/JRE. If you try to use OpenJDK (e.g. for Java 13 or similar) it will not run. This is because of some changes behind the scenes to hidden classes. If you are interested, there are more details here.
If you need to use an OpenJDK version of Java, you may therefore have better luck with the library on which this CSV library is based: see here.
So at the moment I have a class called MySqlConnection with this code inside it
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class MySqlConnection {
public static void Connection() throws Exception {
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Friends", "John", "John123");
// jdbc:mysql://localhost:3306/employee_record --> This is the database
// root is the database user
// root is the password
// Here we create our query
PreparedStatement Statement = con
.prepareStatement("SELECT * FROM names ORDER BY first");
// Creating a variable to execute query
ResultSet result = Statement.executeQuery();
while (result.next()) {
System.out.println(result.getString(1) + " " + result.getString(2));
}
}
}
When I run this, it displays all the results at once in the Eclipse IDE.
http://i.imgur.com/V9kA5fN.png
How do I make it display all the results in a separate window?
You can use JTable on the JFrame to show the data in tabular format on a window. You can find examples on Internet about using JTable.
You can use JTable. Here is my version
public class JResultTable extends JTable {
public DefaultTableModel dataModel;
ResultSet rs;
public void init_model(){
dataModel=new DefaultTableModel();
}
public void add_data() throws SQLException {
String colNames[];
ResultSetMetaData rsMetaData=rs.getMetaData();
int colCount=rsMetaData.getColumnCount();
colNames=new String[colCount];
for(int i=1;i<=colCount;i++)
colNames[i-1]=rsMetaData.getColumnName(i).toUpperCase();
dataModel.setColumnIdentifiers(colNames);
while(rs.next())
{
String[] rowdata= new String[colCount];
for(int i=1;i<=colCount;i++)
rowdata[i-1]=rs.getString(i);
dataModel.addRow(rowdata);
}
}
JResultTable(ResultSet rs) throws SQLException {
super();
init_model();
this.rs=rs;
add_data();
setModel(dataModel);
}
}
Ex- JResultTable mm=new JResultTable(rs)// rs is the resultset. Column Names will automatically become table headers (ResultSetMetaData)
add this mm to a panel or frame.
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.