Java - a GUI update button - java

i am trying to making an update button in my GUI form that can be edit a record in my DB but i missing something that i hope someone to help me
this the code of update method:
public int updateUser(Login user) //int
{
DatabaseConnection dbconn = new DatabaseConnection();
Connection conn = dbconn.getConn();
int rows = 0;
try
{
String sql = "UPDATE LOGIN set USER_NAME = ? , PASSWORD = ? , PRIVILEGE_ID = ?";
PreparedStatement pStm = conn.prepareStatement(sql);
//fill SQL parameters from user: //
pStm.setString(1, user.getUserName());
pStm.setString(2, user.getPassword());
pStm.setInt(3, user.getPrivilegeId());
rows =
pStm.executeUpdate();
}
catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
finally
{
try {
conn.close();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());;
}
}
return rows;
}
code in java swing for update button:
private void updateUserLayerActionPerformed(java.awt.event.ActionEvent evt) {
// 1-get data from user and check it: //
String _name = nameLayer.getText().trim();
String _paswrd = passLayer.getText().trim();
String _prvName = privLayer.getSelectedItem().toString();
//get Privilege_Id from DB:
PrivilegeHandeler prvHndler = new PrivilegeHandeler();
int prvId = prvHndler.getPrivilegeByName(_prvName);
if(_name.length() >0 && _paswrd.length() >0 && prvId> 0)
{
Login user = new Login();
user.setUserName(_name);
user.setPassword(_paswrd);
user.setPrivilegeId(prvId);
//update User: //
loginHandeler loghndlr = new loginHandeler();
int rows =
loghndlr.updateUser(user);
if (rows >0)
{
usrFormErorr.setText("user has been added successfully :)");
nameLayer.setText("");
passLayer.setText("");
privLayer.setSelectedIndex(0);
}
else
{
usrFormErorr.setText("updated failed, try again");
}
}
else
{
usrFormErorr.setText("please, fill the required fields first");
}
}
My problem is this:
1-i am trying to enter an info to edit then update but always get an error updated failed, try again that i made it to get a message when there is a problem
Kindly help. A working code would be very highly appreciated. Thanks in advance.

Related

MySQL searching for data using Java [closed]

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 2 years ago.
Improve this question
I have this code for searching in the MySQL data table by id, but when I run the program it is giving me this error (Output : "Column 'Mart' Not Found"). I'm using JTextFiled to ask the user to enter the id that want to search for.
public void actionPerformed(ActionEvent event) {
if(event.getSource()== btn) {
try {
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement st = connection.prepareStatement("Select ID,user_name_1,password FROM Admin Where ID = ?");
int id = Integer.parseInt(text.getText());
st.setInt(1, id);
ResultSet rs = st.executeQuery();
if(rs.next()==false) {
JOptionPane.showMessageDialog(null, "The ID Not Found!!");
}
else {
String user = rs.getString("user_name_1");
text2.setText(rs.getString(user));
String pass = rs.getString("password");
text3.setText(rs.getString(pass));
}
}
catch (Exception e) {
System.out.print(e.getMessage());
}
}
}
Check if your column names are the same as the ones in the Database
Check if your connection string is connecting to the correct database
Ensure Database Driver is added
Try this:
public class DatabaseClass {
private String url = "YOUR URL";
private String username = "YOUR USERNAME";
private String password = "YOUR PASSWORD";
private static DatabaseClass theDB = new DatabaseClass();
private Connection c;
private DatabaseClass() {
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(url, username, password);
} catch (Exception ex) {
System.out.println("Error Connection: " + ex);
}
}
public Connection getC() {
return this.c;
}
public static DatabaseClass getInstance() {
return theDB;
}
}
And then, the click event:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMap<Integer, String> data = new HashMap<>();
int id = Integer.parseInt(jTextField1.getText());
Connection c = DatabaseClass.getInstance().getC();
PreparedStatement s = c.prepareStatement("select * from yourTable where ID = ?");
s.setInt(1, id);
ResultSet theResult = s.executeQuery();
while (theResult.next()) {
int yourID = theResult.getInt("ID");
String yourData = theResult.getString("Email_Address");
data.put(yourID, yourData);
}
for (HashMap.Entry theEntry : data.entrySet()) {
jTextArea1.append(String.valueOf(theEntry.getKey()) + " " + theEntry.getValue() + "\n");
}
} catch (Exception ex) {
System.out.println("Error: " + ex);
}
}
Ideally this should work, but replace the query with your query and the connection string with yours.

Set User Status as Logged out when Program is closed In Netbeans

I have written a method which sets the status (1) (logged in) when user login.
public void updateLoginStatus(String n) {
conn = DBConnection.ConnectionDB();
String loginStatus = "UPDATE `login` SET `status`=1 WHERE username = ?";
try {
pst = conn.prepareStatement(loginStatus);
pst.setString(1, n);
pst.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
There is another method when the logout button is clicked the user status is set to 0 (logged out)
public void updateLogoutStatus(String n) {
conn = DBConnection.ConnectionDB();
String loginStatus = "UPDATE `login` SET `status`=0 WHERE username = ?";
try {
pst = conn.prepareStatement(loginStatus);
pst.setString(1, n);
pst.executeUpdate();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This works fine, However, when a user clicks the red cross on menubar in the database it shows that the user is logged in but I want to set it to log out. I have found a method
onsetDefaultCloseOperation() but couldn't figure it out what to do. I am a beginner please help.

jFrame fields not saving to db

Am trying to save some field from my jFrame form but when i click the save button, i get the null pointer exception. Previously i was getting the errors that text field couldn't be null so i unchecked not null but it didn't work , i decided not to include Voucher_no in MySQL insert statement as it is an auto increment and its text field is not editable
Is there any problem with my code?
Am Using Mysql Workbench.
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
con.setAutoCommit(false);
try {
// String kb = jTextField3.getText(); //voucher_no
String kc = (String) jComboBox3.getSelectedItem(); //factory
String kg = jTextField10.getText(); //fuel
Double ks = Double.valueOf(kg);
String ke = jTextField11.getText(); //electricity
Double kt = Double.valueOf(ke);
String kf = jTextField12.getText(); //manpower
Double ku = Double.valueOf(kf);
String kj = (String) jComboBox4.getSelectedItem(); //can_name
String kk = (String) jComboBox5.getSelectedItem(); //label name
String kq = jTextField23.getText();//no_of_cans
Double kv = Double.valueOf(kq);
String kr = jTextField24.getText();//no_of_labels
Double kw = Double.valueOf(kr);
String query1= "insert into production (date,factory,fuel,electricity,manpower,can_name,label_name,no_of_cans,no_of_labels)"
+ "values (?,?,?,?,?,?,?,?,?)";
try (PreparedStatement pst = con.prepareStatement(query1)){
// pst.setString(10, kb);
pst.setString(1, ((JTextField) jDate1.getDateEditor().getUiComponent()).getText());
pst.setString(2, kc);
pst.setDouble(3, ks);
pst.setDouble(4, kt);
pst.setDouble(5, ku);
pst.setString(6, kj);
pst.setString(7, kk);
pst.setDouble(8, kv);
pst.setDouble(9, kw);
pst.execute();
}
try {
int rows = jTable2.getRowCount();
for (int row = 0; row < rows; row++) {
String kd = (String) jTable2.getValueAt(row, 0);
Double kn = (Double) jTable2.getValueAt(row, 1);
try {
// Class.forName("com.mysql.jdbc.Driver").newInstance();
// Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/canning?zeroDateTimeBehavior=convertToNull", "root", "");
String query = "insert into production(product_name,product_quantity)"
+ "values (?,?)";
PreparedStatement update = con.prepareStatement(query);
update.setString(1, kd);
update.setDouble(2, kn);
update.addBatch();
update.executeBatch();
con.commit();
} catch (SQLException e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(this, "Error in production Table");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Invalid Entry in fields");
}
} catch (Exception e) {
e.printStackTrace();
// JOptionPane.showMessageDialog(null, "Invalid in fields");
}
} catch (Exception e) {
e.printStackTrace();
}
The code is doing
update.addBatch();
update.executeBatch();
con.commit();
executeBatch and commit must be done outside the loop.
The misunderstanding arises from "addBatch" that should have been named "addToBatch."
Try doing it this way. First create a connection class as follows;
import java.sql.Connection;
import java.sql.DriverManager;
public class db_connection
{
public Connection connection()
throws Exception
{
try
{
Connection conn = null;
String username = "root"; String password = "";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/database";
try {
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
return null;
}
conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}return null;
}
}
Then on your save button do something like this,
private void ButtonRegGroup_SubmitActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if ((this.jTextFieldGrp_ReqAmnt.getText().equals(""))
|| (this.jTextFieldGrp_name.getText().equals(""))
|| (this.jTextFieldGrp_Id.getText().equals(""))
|| (this.jTextFieldGrp_prj_name.getText().equals(""))) {
JOptionPane.showMessageDialog(this, "Some fields are empty", this.title, this.error);
} else {
try {
this.con = ((Connection) new db_connection().connection());
this.pst = ((PreparedStatement) this.con.prepareStatement("insert into registered_projects(project_type,name,project_name,project_id,constituency,ward,requested_amount)values(?,?,?,?,?,?,?)"));
GroupRegDetails();
this.pst.setString(1, this.proj_type);
this.pst.setString(2, this.group_name);
this.pst.setString(3, this.proj_name);
this.pst.setInt(4, this.proj_id);
this.pst.setString(5, this.constituency);
this.pst.setString(6, this.ward);
this.pst.setInt(7, this.requested_amount);
int row = this.pst.executeUpdate();
con.commit();
if (row == 0) {
this.con.rollback();
JOptionPane.showInternalMessageDialog(this, "Didn't Register project", this.title, this.error);
}
JOptionPane.showMessageDialog(this, "Project Successfully Registered", this.title, this.infor);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void GroupRegDetails() {
this.group_name = this.jTextFieldGrp_name.getText();
this.proj_id = Integer.parseInt(this.jTextFieldGrp_Id.getText());
this.proj_name = this.jTextFieldGrp_prj_name.getText();
this.constituency = this.jComboBoxGrp_Comb_const.getSelectedItem().toString();
this.ward = this.jComboBoxGrp_comb_Ward.getSelectedItem().toString();
this.requested_amount = Integer.parseInt(this.jTextFieldGrp_ReqAmnt.getText());
this.proj_type = "Group";
}
And finally good practice is to put fields on a Jpanel and the Jpanel on a Jframe. Hope this helps.

Sqlserver show results in joptionpane with sql query

Hi I want to bring results from a table using SQL query but I am getting the message SQLServerResultSet3 as a result.
I take as an example the below code but it isn't working for me, any idea what I did wrong cause I am new to this ty!
searching from database and showing the output
private void searchquantity(){
//ArrayList <Update_del_insert_products> proList =new ArrayList <Update_del_insert_products> ();
Connection connection =getConnection();
String query ="SELECT * FROM Products WHERE Pro_Quantity <=20";
Statement sts=null;
ResultSet rsr=null;
try{
sts = connection.createStatement();
rsr = sts.executeQuery(query);
//Update_del_insert_products update_del_insert_products ;
if(rsr.next()) {
JOptionPane.showMessageDialog(null,rsr);
}else{
JOptionPane.showMessageDialog(null, "Not Found");
}
}catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
}
=================================================================
private void Check_CapacityActionPerformed(java.awt.event.ActionEvent evt) {
searchquantity();
}
check rows for products that are below 20 in quantity table
private void searchquantity(){
Connection connection =getConnection();
String query ="SELECT * FROM Products WHERE Pro_Quantity <=20";
Statement sts=null;
ResultSet rsr=null;
int a=0;
try{
sts = connection.createStatement();
rsr = sts.executeQuery(query);
while(rsr.next()) {
JOptionPane.showMessageDialog(null,rsr.getString("Pro_Id"));
JOptionPane.showMessageDialog(null,rsr.getString("Pro_Name"));
a=1;
}
if (a==0){
JOptionPane.showMessageDialog(null, "Not Found");
a=0;}
}catch (Exception e) { JOptionPane.showMessageDialog(null, e); }
}

How to auto refresh jComboBox data after update?

I have a jComboBox that getting data from MySQL server database.
When I add new data to database, the jComboBox doesn't show it, and I must reopen my program to add the new data to jComboBox.
How can I refresh jComboBox data automatically?
This is my code :
private void dataComboBox(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select id from perfume order by id asc";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0] = res.getString(1);
jComboBox5.addItem(ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
private void showCBdata(){
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/shop","root","");
Statement stat = con.createStatement();
String sql = "select name from perfume where id='"+jComboBox5.getSelectedItem()+"'";
ResultSet res = stat.executeQuery(sql);
while(res.next()){
Object[] ob = new Object[3];
ob[0]= res.getString(1);
jTextField8.setText((String) ob[0]);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
//call method
private void jComboBox5ActionPerformed(java.awt.event.ActionEvent evt) {
showCBdata();
}
can you help me?
thank you..
You can do it in this way it will automatically refresh the combobox
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
removeAllItems(); method will clean the combobox to insure that not to repeat values.
You do not need to create a separate Object to add in jComboBox instead you can add String too.
Inzimam Tariq IT's Code (above):
try {
comboBox.removeAllItems();
sql = "SELECT * FROM `table_name`";
rs = stmnt.executeQuery(sql);
while (rs.next()) {
String val = rs.getString("column_name");
comboBox.addItem(val);
}
} catch (SQLException ex) {
Logger.getLogger(DefineCustomer.class.getName()).log(Level.SEVERE, null, ex);
}
I suggest putting all of this code inside an ActionListener. So that each time there the mouse is entered over the comboBox the above code will run. You should do the following:
public void mouseEntered(MouseEvent e) {
//the above code goes here
}
I suggest using a mouseListener:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
But if you want to look at other ActionListeners you can see them here:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Once you add a new registry in the DB, do a removeAllItems comboBox.removeAllItems(); and repopulate de combobox,
My example:
jComboLicorerias.removeAllItems();
try {
Conector = Conecta.getConexion();
Statement St = Conector.createStatement();
try (ResultSet Rs = St.executeQuery(Query)) {
while (Rs.next()) {
jComboLicorerias.addItem(Rs.getString("nombreLicoreria"));
}
St.close();
}
} catch (SQLException sqle) {
JOptionPane.showMessageDialog(null, "Error en la consulta.");

Categories