I have this project and I need to get data (writing) from a database and I am using javaFX. I have a connection class that works (when I run it makes the connection)
public class Conexiune extends JPanel {
public Connection con = null;
public Statement stmt = null;
public ResultSet rs = null;
Vector data = null;
Vector columns = null;
JTable table;
JPanel paneOrar;
JTable tabel;
void login() throws SQLException {
String url = "jdbc:mysql://localhost:3308/database";
String login = "root";
String password = "password";
con = (Connection) DriverManager.getConnection(url, login, password);
}
Component query() throws SQLException {
stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM data");
ResultSetMetaData md = (ResultSetMetaData) result.getMetaData();
int columnCount = md.getColumnCount();
Vector columns = new Vector(columnCount);
// store column names
for (int i = 1; i <= columnCount; i++)
columns.add(md.getColumnName(i));
Vector data = new Vector();
Vector row;
// store row data
while (result.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
data.add(row);
}
JScrollPane scrollPane = new JScrollPane(tabel);
this.setLayout(null);
JTable table = new JTable(data, columns);
return this.add(table);
}
Conexiune() {
try {
login();
System.out.println("bdConnect");
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
After I run I get the message bdConnect with no errors.
The main problem is that i don't know what to do after, I mean I want to get the text from the database on to something that is not a table. Something like a scrollPane. Lets say i just want a window full of text on multiple lines but not a table. Lets say that you want to get the contents of a book from your database, you cant put it in a table. Can anyone help me please I'm getting kind of desperate!!!
Related
I want to use a MySQL with JDBC in a loop, because I have to poll a table frequently for new data which comes in from other clients. But even if I close the ResultSet, the connection and the statement, is the old result at the next round still there. I cannot get a new result, unless I restart the program. What is my mistake?
I condensed the code for the necessary.
import java.sql.*;
public class Eventmgr {private static String in_text;
private static String in_typ;
private static Connection connection;
private static String URL = "jdbc:mysql://xxx.xxx.x.x:3306/xxxx";
private static String username = "xxx";
private static String password = "xxx";
public static void start() throws SQLException {
while(loop_count > 0) {
if (loop == false) {
loop_count = loop_count -1;}
connection = DriverManager.getConnection(URL, username, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select id, nummer, text, typ from inbox order by id asc limit 1") ;
while(rs.next()) {
in_id = rs.getString("id");
in_nummer = rs.getString("nummer");
in_text = rs.getString("text");
in_typ = rs.getString("typ");}
connection.close();
stmt.close();
rs.close();
System.out.println("still running");
}
}
}
Anybody has an idea what my problem is?
Thanks in advance
I am stupid, and it was my mistake...
The problem is. I check on the variable "in_id" and if there is no new result "while(rs.next())" dont deliver a new value, so I need to reset that variable with "in_id = null;" at the end of the loop.
Now it works...
My code currently goes as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
String[] data = parentIds.toArray(new String[parentIds.size()]);
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (?)";
stmt = conn.prepareStatement(sql);
data = parentIds.toArray(data);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
However even though in the unit tests I try to pass an array with parentIds, the return remains null.
What I can gauge from this is one of the following:
The array data isn't getting properly read, therefore the output is coming as null.
WHERE IN is not supported by h2 or else there is a different implementation that needs to be used instead.
Where am I going wrong in this?
EDIT - There was a similar duplicate question that was tagged. While it suggested using a StringBuilder and a loop, I was looking for an answer stating how it could be done in a cleaner way using the query itself.
Try setting the parameter as a list instead of an array, ie replace
stmt.setObject(1, data);
with
stmt.setObject(1, Arrays.asList(data));
Figured it out.
There was an issue posted on the h2database GitHub about this exact problem. Followed the suggested edits and it worked!
Code after edits is as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
Object[] data = parentIds.toArray();
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (SELECT * FROM TABLE(x VARCHAR = ?))";
stmt = conn.prepareStatement(sql);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
As you can see, I've used an Object array for data instead and added an additional query inside the main query.
Followed the instructions given in the GitHub issue to a tee and it worked flawlessly.
I'm trying to display images from database into jlabel
IMAGES = column name, currentuser.getText() = i have a text on the top which determines the column USERNAME in my database
EDITED - I really dunno what to do anymore, it's been a week but still i cant display the image from the database
public class MyProfile extends JFrame implements ActionListener{
Container c;
ResultSet rs;
Connection con;
Statement st;
TempData temp = new TempData(); //Class for storing current user who logins (Set & get)
JLabel currentuser = new JLabel("" + temp.getUsername());
JLabel displayPhoto = new JLabel();
public MyProfile() {
super("My Profile");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1175, 698);
this.setLocationRelativeTo(null);
this.setVisible(true)
c = this.getContentPane();
c.setLayout(null);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/pancakefinder", "root", "");
st = con.createStatement();
} catch (Exception exp) {
}
c.add(currentuser);
currentuser.setFont(new Font("Times New Roman", Font.PLAIN, 20));
currentuser.setForeground(Color.orange);
c.add(displayPhoto);
displayPhoto.setBounds(160, 330, 250, 230);
displayPhoto();
}
public void displayPhoto() {
try {
PreparedStatement pst = null;
rs = null;
pst = con.prepareStatement("select IMAGES from images where USERNAME = '" + currentuser.getText() + "'");
rs = pst.executeQuery();
byte[] bytes = null;
if (rs.next()) {
bytes = rs.getBytes("images");
Image img = Toolkit.getDefaultToolkit().createImage(bytes);
displayPhoto.setIcon(new ImageIcon((img)));
displayPanel.add(displayPhoto);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(Stringp[] args){
MyProfile ex = new MyProfile();
}
}
I'm guessing that displayPanel is a JPanel and displayPhoto is the JLabel. If displayPhoto was added before pack(), setIcon() should be enough. If not, you'll need to revalidate() the panel after add(). Also check if the rs.next() result is false, and remember that it will only fetch one row; you'll need a loop to get any other rows.
I have problem when trying to fetch the data from database and display in database. I get from user input and store as a search variable. This is how I set up my table:
//I get the user input to perform search
#FXML
public void searchResident(ActionEvent event){
String search=getTb_search().getText();
if(search.equals("")){
Dialogs.showErrorDialog(null, "Please enter something", "Blank fields detected", "");
}else{
setUpSearchTable(search);
}
}
//How I set up my table
public void setUpSearchTable(String search) {
TableColumn rmNameCol = new TableColumn("Name");
rmNameCol.setVisible(true);
rmNameCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<SearchNeedyResidentController, String>, ObservableValue<String>>() {
public ObservableValue<String> call(TableColumn.CellDataFeatures<SearchNeedyResidentController, String> p) {
return p.getValue().searchNameProperty();
}
});
TableColumn rmNricCol = new TableColumn("NRIC");
rmNricCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_nric"));
rmNricCol.setMinWidth(150);
TableColumn rmPhNoCol = new TableColumn("Phone Number");
rmPhNoCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController,String>("search_phNo"));
rmPhNoCol.setMinWidth(350);
TableColumn rmIncomeCol = new TableColumn("Income($)");
rmIncomeCol.setCellValueFactory(new PropertyValueFactory<SearchNeedyResidentController, String>("search_income"));
rmIncomeCol.setMinWidth(100);
ResidentManagement.entity.NeedyResidentEntity searchValue= new ResidentManagement.entity.NeedyResidentEntity();
//viewProduct.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
table_search.setEditable(false);
table_search.getColumns().addAll(rmNricCol, rmNameCol, rmIncomeCol, rmPhNoCol);
table_search.getItems().setAll(searchValue.searchResident(search));
}
}
//How I populate the table data
public List<SearchNeedyResidentController> searchResident(String search){
List ll = new LinkedList();
try {
DBController db = new DBController();
db.getConnection();
String sql = "SELECT * FROM rm_needyresident WHERE name LIKE '" + search + "%'";
ResultSet rs = null;
// Call readRequest to get the result
rs = db.readRequest(sql);
while (rs.next()) {
String nric=rs.getString("nric");
String name = rs.getString("name");
double income = rs.getDouble("familyIncome");
String incomeStr = new DecimalFormat("##.00").format(income);
String phNo = rs.getString("phNo");
SearchNeedyResidentController row = new SearchNeedyResidentController();
row.setSearchNric(nric);
row.setSearchName(name);
row.setSearchIncome(incomeStr);
row.setSearchPhNo(phNo);
ll.add(row);
}
rs.close();
} catch (SQLException ex) {
ex.printStackTrace();
System.out.println("Error SQL!!!");
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
return ll;
}
}
When search button is on click, the table column is displayed. However, it's just show a blank table even though there's matching result. I debug already and I think the error is at the retrieving data in the searchResident method. It's not retriving the data from database. Anybody know what's wrong?
Thanks in advance.
try dis one...
#FXML private void SearchButton()
{
Connection c ;
datamem = FXCollections.observableArrayList();
try
{
c = Dao.getCon();
String SQL =SELECT * FROM `Member`;
ResultSet rs = c.createStatement().executeQuery(SQL);
if(table.getColumns().isEmpty())
{
for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++)
{
final int j = i;
TableColumn col = new TableColumn(rs.getMetaData().getColumnName(i+1));
col.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<ObservableList,String>,ObservableValue<String>>(){
public ObservableValue<String> call(TableColumn.CellDataFeatures<ObservableList, String> param) {
return new SimpleStringProperty(param.getValue().get(j).toString());
}
});
table.getColumns().addAll(col);
}//for
}//if
while(rs.next())
{
ObservableList<String> row = FXCollections.observableArrayList();
for(int i=1 ; i<=rs.getMetaData().getColumnCount(); i++)
{
row.add(rs.getString(i));
}// for
datamem.add(row);
}//while
table.setItems(datamem);
}//try
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "Problem in Search Button "+e);
}
}//else
}//else
} //search method
I am trying to display the database records in the Jtable but i m not getting the code right. I m using IDE netbeans and database is mysql. I can see the panel and the scroll pane but the table is not displayed. I think something is wrong in the table properties or dont know if its invisible.
My code is as follows:
try{
panel_paylist.setVisible(true);
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(dbUrl,"root","17121990");
System.out.println("Connected!!!!");
MainScreen obj = new MainScreen(conn);
String[] columnNames = {"First Name",
"Last Name",
"Amount Recvd.",
"Date","Cheque/cash","cheque no","Balance Amt.","Total Amt.",
"Vegetarian"};
ResultSet rs = null;
Statement sql= null;
ArrayList<Object[]> data = new ArrayList<>();
String query="SELECT firstname,lastname, amountreceivd,dte,creditcashcheque,cheque_no,balance_amt, totalamount,Remark FROM payment;";
sql = con.createStatement();
sql.executeQuery(query);
rs = sql.getResultSet();
while(rs.next()){
Object[] row = new Object[]{rs.getString(1),
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7),
rs.getInt(8),
rs.getString(9)};
data.add(row);
}
Object[][] realData = data.toArray(new Object[data.size()][]);
table_paylist= new JTable(realData, columnNames);
scroll_paylist= new JScrollPane(table_paylist);
table_paylist.setPreferredScrollableViewportSize(new Dimension(800, 200));
table_paylist.setFillsViewportHeight(true);
panel_paylist.setLayout(new BorderLayout());
panel_paylist.add(scroll_paylist, BorderLayout.CENTER);
}
catch(Exception e)
{
}
please help
first of all you are missing port number of localhost.
change
"jdbc:mysql://localhost/hostel"
to
"jdbc:mysql://localhost:3306/hostel";
second point dont use semicolon(;) at the end of sql string. i. e. remove semicolon from
"SELECT firstname,lastname, amountreceivd,dte,creditcashcheque,cheque_no,balance_amt, totalamount,Remark FROM payment;"
and you can also try this one
public DefaultTableModel PlayList() throws ClassNotFoundException,SQLException,ParseException
{
String[] columnNames = {"First Name","Last Name","Amount Recvd.","Date","Cheque/cash","cheque no","Balance Amt.","Total Amt.","Vegetarian"};
DefaultTableModel dtm = new DefaultTableModel(columnNames , 0);
dtm.setColumnCount(9);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:8080/hostel","root","17121990");
PreparedStatement ps1 = null;
ResultSet rs1 = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
ps1=conn.prepareStatement("SELECT firstname,lastname,mountreceivd,dte,creditcashcheque,cheque_no,balance_amt,totalamount,Remark FROM payment");
rs1 = ps1.executeQuery();
while(rs1.next())
{
dtm.addRow(new Object[]{rs1.getString(1)
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7),
rs.getInt(8),
rs.getString(9)});
}
}
finally
{
rs1.close();
ps1.close();
conn.close();
}
return dtm;
}
now use PlayList() method as a argument of your jtable's setmodel method;
i. e. jtable.setmodel(PlayList());
Use rs2xml third party Jar file to display query results.This is very helpful