How to define a Label class in MyEclipse? - java

I have set many lables and I want them to show the data from database.But it shows"com.myql.jdbc.JDBC4ResultSet"
The sql sentences' results are double
And there is the code as follows
private void initData() {
initCondition("select sum(initAmount) from account", lblInit);
initCondition("select sum(amount) from detail where directionid = 1", lblIncome);
initCondition("select sum(amount) from detail where directionid = 2", lblOutcome);
lblAsset.setText("as");
}
//It's my definition about the label class.
private void initCondition(String sql, JLabel jLabel) {
try {
Connection connection = DriverManager.getConnection(url, user,
password);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
jLabel.setText(resultSet.toString());
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
// TODO: handle exception
}

The result of sql is a double number. I think the resultset needn't loop.
Are you saying the result set contains just one column of data in one row? In that case, maybe something along the lines of..
ResultSet resultSet = statement.executeQuery(sql);
resultSet.first();
jLabel.setText("" + resultSet.getDouble(1));

Related

How do I pass data values from a particular column or field in a database into a variable in java?

Is there a way to pass data values for a MySQL database into a variable in Java?
This is what I have tried so far:
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Login", "root", "****");
String query = "Select username, passphrase from student where username=?";
statement = connection.prepareStatement(query);
resultSet = statement.executeQuery(query);
if (resultSet.next()) {
_name = resultSet.getString(2);
_pass_phrase = resultSet.getString(3);
}
} catch (Exception e) {
System.out.println(Arrays.toString(e.getStackTrace()));
assert resultSet != null;
resultSet.close();
statement.close();
}
but I keep on getting a NullPointerException that points to my _name variable, telling me it empty. Could someone please point out to me what it is doing, and how to correct it?

Unable to execute prepared Statement from DAO

So currently Im trying to do get the auto-incremented primary key by following this answer
Primary key from inserted row jdbc? but apparently the program can't even reach that line and the error appeared on the ps.executeQuery() line after debugging the program, the error it display was only "executeQuery" is not a known variable in the current context. that line, which didn't make sense to me. So how do I go pass this hurdle?
public static int createNewLoginUsers(String newPassword, String newRole) throws SQLException{
Connection conn = DBConnection.getConnection();
Statement st = null;
ResultSet rs = null;
PreparedStatement ps = null;
int id = 0;
try{
String sql = "INSERT into Login(password, role) VALUES(?,?)";
ps = conn.prepareStatement(sql);
ps.setString(1, newPassword);
ps.setString(2, newRole);
ps.executeUpdate();
st = conn.createStatement();
rs = st.executeQuery("SELECT * from Login");
rs.last();
System.out.println(rs.getInt("username"));
id = rs.getInt("username");
rs.close();
} finally{
try{
conn.close();
}catch(SQLException e){
System.out.println(e);
}
}
return id;
}
The part of the method which calls the createNewLoginUsers method
if(newPasstxtfld.getText().equals(retypeNewPasstxtfld.getText())){
//update into database
try {
int username = CreateUsersDAO.createNewLoginUsers( (String) newUserRoleBox.getSelectionModel().getSelectedItem(), newPasstxtfld.getText());
Alert confirmation = new Alert(Alert.AlertType.INFORMATION);
confirmation.setHeaderText("New User Details has been created. Your username is " + username);
confirmation.showAndWait();
} catch (SQLException e) {
}
EDIT:
Databases table added and it's in the provided link below
https://imgur.com/a/Dggp2kc and edit to the codes instead of 2 try blocks in one method i have placed it into a different similar method, updated my codes to the current one I have.

Retrieving data from database and increment by one

I am trying to retrieve a data (ID No.) from a database (MySQL) and add it by one. However, when I try to put this code below, when I try to build it, the form doesn't show up. But when I try to remove the Connection cn line, the form with finally show up. I had another project with this code it it worked perfectly fine. I'm not sure why its not working on this one.
public Abstract() throws Exception {
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
initComponents();
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT ID from bidding_abstractofprices";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
while(rs.next()){
int id = Integer.parseInt(rs.getString("ID")) + 1;
lblTransacID.setText(String.valueOf(id));
}
}catch (Exception ex){
}
}
What it looks like you are trying to do is to get the ID field value from the last record contained within the bidding_abstractofprices Table contained within your Database and then increment that ID value by one (please correct me if I'm wrong). I don't care why but I can easily assume. Here is how I might do it:
public Abstract() throws Exception {
// Allow all your components to initialize first.
initComponents();
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/user?zeroDateTimeBehavior=convertToNull","root","");
Statement st = null;
ResultSet rs;
try {
String sql = "SELECT * FROM bidding_abstractofprices ORDER BY ID DESC LIMIT 1;";
st = cn.prepareStatement(sql);
rs = st.executeQuery(sql);
int id = 0;
while(rs.next()){
id = rs.getInt("ID") + 1;
}
lblTransacID.setText(String.valueOf(id));
rs.close();
st.close();
cn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}

How to remove data in database from jTable?

I want to remove the data in database from jtable. I have 1 jTextField and 1 jButton. So when i click this selected row in table, the primary key wont set in my jTextField.
Is it possible to remove the data in database from jtable without jTextField and just a button?
Heres my code
try {
int row = table.getSelectedRow();
String id_ = (table.getModel().getValueAt(row, 1)).toString();
String sql ="SELECT id FROM 'mycredentials.sales' WHERE id= "+id_+"'";
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
PreparedStatement pst = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
jFrame_removeP.setText(rs.getString("id"));
}
} catch (SQLException e1) {
System.err.println(e1);
}
Random id number appears in my jTextField. And my table code is:
String name = jFrame_pName.getText().trim();
String price = jFrame_pPrice.getText().trim();
String quantity = jFrame_quantity.getText().trim();
String total = jFrame_total.getText().trim();
String st[] = {name, price, quantity, total};
model.addRow(st);
jFrame_gTotal.setText(Integer.toString(getSum()));
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement s = (Statement) connection.createStatement();
String sql = "INSERT INTO mycredentials.sales (name, price, quantity, total) VALUES ('"+jFrame_pName.getText()+"', '" + jFrame_pPrice.getText() + "','"+jFrame_quantity.getText()+"','"+jFrame_total.getText()+"')";
s.executeUpdate(sql);
} catch (SQLException e1) {
System.err.println(e1);
}
And my remove button is:
DefaultTableModel model1 = (DefaultTableModel) table_1.getModel();
int selectedRowIndex = table_1.getSelectedRow();
model1.removeRow(selectedRowIndex);
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mycredentials?autoReconnect=true&useSSL=false", username, password);
Statement ps = (Statement) connection.createStatement();
String sql = "DELETE from mycredentials.sales where id ='" + jFrame_removeP.getText() + "'";
ps.executeUpdate(sql);
} catch (Exception ex) {
System.err.println(ex);
}
Do you mean like this? I didn't get exactly what you needed. Hope this helps.
private void deleteBtnActionPerformed(java.awt.event.ActionEvent evt) {
String deleteQuery = "DELETE FROM SAMPLE WHERE USER_ID = ?";
try (Connection myCon = DBUtilities.getConnection(DBType.JDBC);
PreparedStatement myPs = myCon.prepareStatement(deleteQuery);){
myPs.setInt(1,userID);
myPs.executeUpdate();
JOptionPane.showMessageDialog(null,"Records deleted");
}//end of try
catch (SQLException ex) {
DBUtilities.processException(ex);
}//end of catch
}
After search a record. You just click a record in the Jtable you want to delete. And just hit the Delete Button simple as that.
Just use a refresh method here if you want to remove the selected row. Fix your statement much better if you use Prepared Statement than Statements to avoid SQL injection.

Fetch a column into the result set which is not in the table

My Title might not be clear enough. So let me explain the problem . I have to retrieve the values from the database store it in an array list and display it in a jsp page dynamically. for that am using a query
select customer,
id,
0 message
from TableName
My Table Structure:
customer varchar2(20)
id Number
I don't know how to add the column 0 message into the result set since this column is not present in that table.
For example, if we give
select 0 message
from TableName;
The output of the above query will be
message
0
So now my question is how to add this column(message) into my Resultset and Array list?
When you add it to your SQL-query as in your question it should also appear in the resultset...
Just wondering if you are facing any issue with executing the SQL query with the additional (non-existing in DB) column through JDBC.
for eg: - you can execute the below query directly in the database through JDBC
select customer,
id,
0 "message"
from TableName
Sample Code snippet.
Connection conn = DriverManager.getConnection(".....", "...","..");
ps = conn.prepareStatement("select customer, id, 0 \"message\" from your_table");
ResultSet rs = ps.executeQuery();
while(rs.next()){
System.out.printf("%s %s %s", rs.getString("id"), rs.getString("customer"), rs.getString("message"));
}
Hlo.. below code will help you..
package com.smk.jdbc.ps;
import java.util.ArrayList;
public class PreparedStatement {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.OracleDriver");
java.sql.Connection conn = null;
java.sql.PreparedStatement ps = null;
String strQry = "select 1 message from dual where 1 = ?";
conn = java.sql.DriverManager.getConnection("jdbc:oracle:thin:#localhost:wzdev", "user","pwd");
ps = conn.prepareStatement(strQry);
ps.setInt(1, 1);
java.sql.ResultSet rs = ps.executeQuery();
while(rs.next()){
java.util.ArrayList<java.sql.ResultSet> ars = new ArrayList<java.sql.ResultSet>();
ars.add(rs);
System.out.println(ars.get(0).getInt("message"));
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
}
}
This code is working fine for sql server.And doing same for whatever u want.
public class ConnectionPool
{
public static void main(String[] args)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("","","");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("select sRowId, 0 messa from tblAccount");
while(rs.next())
{
list.add(rs.getInt("messa"));
}
System.out.println(list.size());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

Categories