How do I subtract an input from jtextfield to mysql database? - java

How do i subract an input from mysql database?
Let's say I'm doing a bill and inventory system. So when the user input a quantity on a jtextfield, it'd minus off from the table.
will attach the GUI.
right now, i have written this method
public boolean updateBill(Bill bi) {
boolean success = false;
dbController db = new dbController();
PreparedStatement ps;
try {
myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
Statement myStatement = myConn.createStatement();
String sql = "UPDATE medicalproduct SET quantity = quantity - ? WHERE productID = ?, productName = ?, dosage = ?, price = ?, status = ?" ;
myStatement.executeUpdate(sql);
myConn.close();
} catch (Exception e) {
e.printStackTrace();
}
return success;
}
but then I do not know what to write on my actionPerform and how to link my jtextfield to the sql query.
This is how my gui looks like

Your sql statement is invalid anyway... But if am right, all you want to do is subtract from a field in the database by the value specified in a jTextField
//For example quantity -= txtfieldValue;
If does what you want. You can query for the value of the field, do the subtraction and then finally update the field. Here is an example for updating only the quantity:
public void updateQuantity(String txtFieldValue,String id) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!!!");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ooadp?useSSL=false", "root", "pass");
System.out.println("Connection created!!!");
PreparedStatement pState;
String sqlRawP1 ="select quantity from medicalproduct where productID=?";//I guess medicalproduct is your table name
pState = conn.prepareStatement(sqlRawP1);
pState.setString(1, id);
ResultSet rSetQuantity = pState.executeQuery();
int countQuantity = 0;
while(rSetQuantity.next()){
countQuantity = rSetQuantity.getInt(1);//Am assumming that quantity is an integer
}
int value = Interger.parseInt(txtFieldValue);
countQuantity-= value;
String sqlRawP2 = "update medicalproduct set quantity=? where productID=?";
pState = conn.prepareStatement(sqlRawP2);
pState.setInt(1,countQuantity);
pState.setString(2, id);
pState.executeUpdate();
}
Hope it will work well..Forgive me if there are minor errors because I haven't tested it myself.

Related

Truncated incorrect DOUBLE value using DELETE statement

int d1;
String attribute = comboBox1.getSelectedItem().toString(); // a combo box
System.out.println(attribute);
String data = t.getText(); // a textfield
System.out.println(data);
if (attribute.equals("COURSE_ID")) {
IsNumber in = new IsNumber();
d1 = in.stringToInt(data);
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "DELETE FROM course WHERE ? = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, attribute);
statement.setInt(2, d1);
boolean rows = statement.execute();
if (rows == true) {
new ViewDatabase(user, name, pswrd);
System.out.println("COURSE_ID UNIT UPDATE SUCCESSFUL!");
frame.setVisible(false);
} else if (rows == false) {
JOptionPane.showMessageDialog(null, "Cannot find row!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
For this piece of code, whenever I try to run it, it returns "Data truncation: Truncated incorrect DOUBLE value: 'COURSE_ID'". I'm not sure what this is referring to and I searched and found some people saying that this error message is misleading, though I only found answers to selects, inserts, and updates, but not deletes.
I also turned off strict mode in MySQL, as advised from the internet, but to no avail.
You can't bind strings to actual column names in a prepared statement. So, the attribute column names must be hard-coded. One pattern which might work would be:
String sql = "";
if ("COL1".equals(attribute)) {
sql = "DELETE FROM course WHERE COL1 = ?";
}
else if ("COL2".equals(attribute)) {
sql = "DELETE FROM course WHERE COL2 = ?";
}
else {
sql = "DELETE FROM course WHERE COL3 = ?";
}
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, d1);
boolean rows = statement.execute();

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.

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.

SQL queries in Java: (JDBC) How to use the SELECT statement?

MysqlDatabase
This is my query to connect to my database.
SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam
FROM speler
WHERE Spel_Naam = ?
I work in the console of netbeans. When I want to show the records of table Speler with the Spel_Naam.
In the console I want to type a primary key of the table Spel and then it shows me the records of the table Speler in the console. How can I do this.
Like WHERE Spel_Naam = ?
The question mark need to be the name that I typed in
Is the select statement correct? I want to type the Spel_Naam in the console and then It must connect to the database and give me the records of table Speler. How can I do this?
public class SpelerMapper
{
private final static String LEES_SPELERS_SQL = "SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam FROM speler WHERE Spel_Naam = ?";
public List<Speler> geefSpelers()
{
List<Speler> spelerLijst = new ArrayList<Speler>();
Statement statement;
Connection connection = PersistentieController.getInstance().getConnection();
try
{
statement = connection.createStatement();
// query database
ResultSet resultSet = statement.executeQuery(LEES_SPELERS_SQL);
while (resultSet.next())
{
String naam = resultSet.getString("naam");
String kleur = resultSet.getString("kleur");
int sector = resultSet.getInt("sector");
int aantalZilverstukken = resultSet.getInt("aantalZilverstukken");
Speler speler = new Speler(naam ,kleur, sector , aantalZilverstukken);
spelerLijst.add(speler);
}
statement.close();
return spelerLijst;
} catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
Use PreparedStatements:
String LEES_SPELERS_SQL = "SELECT ... WHERE Spel_Naam = ?";
PreparedStatement prepStmt = con.prepareStatement(LEES_SPELERS_SQL);
prepStmt.setString(1, naam);
ResultSet rs = prepStmt.executeQuery();
Additional note: while being another option, concatenation of the SQL query is an unsafe way of doing the same task. Refer to this article for more info.

Displaying datatable from database

I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.

Categories