How to multiply 2 columns in database MySQL using JAVA GUI? - java

I want to make a sales database that it will insert and insert the data. My id is AUTO INCREMENT.
My Code is Here:
Inserting Data
String sql = "INSERT INTO `mycredentials`.`sales` (name, price,quantity)
VALUES ('"+jFrame_pName.getText()+"', '" + jFrame_pPrice.getText() + "','"+jFrame_quantity.getText()+"')";
ps.executeUpdate(sql);
Updating Data:
String sql2 = "UPDATE `mycredentials`.`sales` SET quantity = '"+jFrame_quantity.getText()+"', total = (quantity*price) WHERE id ='?'";
ps.executeUpdate(sql2);
And Viewing Data:
String sql1 = "SELECT name AS 'Product Name', price AS 'Product Price', quantity as 'Quantity', total as 'Total' FROM `mycredentials`.`sales`";
ResultSet rs = ps.executeQuery(sql1);
table_1.setModel(DbUtils.resultSetToTableModel(rs));
But the displays makes the total NULL. What is my error? Thank you so much.

Have you tried to maybe specify again the quantity like this?
String sql2 = "UPDATE `mycredentials`.`sales` SET quantity = '"
+ jFrame_quantity.getText() + "', total = ("
+ jFrame_quantity.getText() + "*price) WHERE id ='?'";
ps.executeUpdate(sql2);

Related

using select statement to set a Resultset into a single cell in sql

I'm trying to set a value from a Resultset into a single cell in another column....
the table is something like this
idnumber courseCode remarks semester
12/073. CPE302. Fail. 2
12/073. CPE304. Pass. 1
12/074. CPE302. Pass. 2
12/073. EEE401. Fail. 1
12/074. CPE304. Pass. 1
...what I want to do is select the courseCode where idnumber=12/073 and remarks=Fail,using the result I want to update another table cgpa, a single Cell in cgpa that has a column name remarks with the Resultset.
Here is what I tried:
try {
String value=isearch.getText();
String value1="Fail";
String sql=" select courseCode from ResultUpload where idnumber='" + value + "' and remarks='" + value1 + "' ";
pst.conn.preparedStatement(sql);
pst.executeQuery();
while(rs.next()){
String course = rs.getString("courseCode");
String sql1="update cgpa set remarks='" + course + "' where idnumber='" + value + "' ";
pst.conn.preparedStatement(sql);
pst.execute();
}
}

SQLite delete a specific row java swing

I'm trying to delete a specific row from a table, and I can't find the way to do it.
I was following https://groups.google.com/forum/#!topic/android-developers/rrmbsKyKRCE but it didn't work.
my query is:
String query = "delete from " + type + " where name=? and score =? (SELECT score FROM " + type + " ORDER BY score DESC LIMIT 1)";
pst.setString(1, tempName);
pst.setInt(2, tempScore);
The string "type" is the table name (no bugs with the table name) and in the table I have to rows: name and score. and pst is the prepared statement.
The error I get: "[SQLITE_ERROR] SQL error or missing database (near "(": syntax error)".
I've noticed that the link above is for android, but I couldn't find something for java swing...
What am I doing wrong?
It seems you're looking for an IN clause
String query = "delete from " + type + " where name=? and score IN (SELECT score FROM " + type + " ORDER BY score DESC LIMIT 1)";

Inserting a value to a Foreign key using java and database

i need some solution from my foreign key in inserting a FK ID the problem is when i insert the ID, and the Payment it will insert first Customer_ID and the second is default to null value and on next column it will set to the inserted and the other one is null here's my code
pStmt2 = conn.prepareStatement("insert into Audittrail_tbl (Customer_ID) values ((Select Name_ID from Customer_tbl where FName ='"+txtFName.getText()+"' and LName = '"+txtLName.getText()+"'))");
pStmt2 = conn.prepareStatement("insert into Audittrail_tbl (Payment) values ('"+txtPayment.getText()+"')");
pStmt2.executeUpdate();
Your code should be:
String sql = "insert into Audittrail_tbl (Customer_ID, Payment)" +
" select Name_ID, ?" +
" from Customer_tbl" +
" where FName = ?" +
" and LName = ?";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, txtPayment.getText());
stmt.setString(2, txtFName.getText());
stmt.setString(3, txtLName.getText());
stmt.executeUpdate();
}
Or better yet, if Payment is an amount column:
// Using BigDecimal
stmt.setBigDecimal(1, new BigDecimal(txtPayment.getText()));
// Using Double
stmt.setDouble(1, Double.parseDouble(txtPayment.getText()));
Since that will parse the text to number in Java code, where you can better handle parse errors.
Note: Using insert-from-select, instead of insert-values with a subquery, will allow you to select multiple columns from Customer_tbl if needed.
You're doing two inserts, which creates two records. if you want to update the record created by the first query, you need to UPDATE for the second query instead.
And why use two queries? Why not
pStmt2 = conn.prepareStatement("
insert into Audittrail_tbl (Customer_ID, Payment)
values (
(Select Name_ID from Customer_tbl where FName ='"+txtFName.getText()+"' and LName = '"+txtLName.getText()+"'),
'"+txtPayment.getText()+"')");)");
Of course, that won't work as-is (I'm too lazy to check quote/bracket matching), but should give you the general idea.

Updating SQL Table with Java

I am developing an application that can update my database... However, I can't get my Java method working correctly. It gives me the following error: Must declare the scalar variable "#P0WHERE". Any suggestions?
The method I am using:
public void updateTable() throws SQLException
{
Scanner input = new Scanner(System.in);
System.out.println("Update the following:\n" + this);
this.getReservationInfo(input);
DataConnection connection = new DataConnection();
String query = "UPDATE " + TableName;
query += "Set Name = ?";
query += "WHERE Person_ID = " + id;
connection.updateData(query, person_name);
connection.closeConnection();
}
Add spaces before 'SET' and 'WHERE', otherwise it will not work.
String query = "UPDATE " + TableName;
query += " SET Name = ?";
query += " , Age = ?";
query += " , Col1 = ?"; //And other cols
query += " WHERE Person_ID = " + id;
EDIT: Changed query to update multiple columns.
I think so. You seem to be missing spaces. After the TableName and after the ?.
String query = "UPDATE " + TableName;
query += " Set Name = ?"; // tableSet not good, and
// ?WHERE is not valid add spaces.
query += " WHERE Person_ID = " + id;

Column count doesn't match value count at row 1 - Java SQL [duplicate]

This question already has answers here:
java.sql.SQLException: Column count doesn't match value count at row 1
(3 answers)
Closed 6 years ago.
I am getting the "Column count doesn't match value count at row 1" but I couldn't seem to fix it. I tried changing the quotation marks and data type but still no luck. Can anyone see where I've gone wrong?
public void actionPerformed(ActionEvent arg0) {
if(!textField.getText().isEmpty() && !textField_1.getText().isEmpty() && !textField_2.getText().isEmpty() && !textField_3.getText().isEmpty() && !textField_4.getText().isEmpty() && !textField_5.getText().isEmpty() && !textField_6.getText().isEmpty() && !textField_7.getText().isEmpty())
{
String moduleName = textField.getText();
String studId = textField_1.getText();
String sFName = textField_2.getText();
String sLName = textField_3.getText();
int weekNo = Integer.parseInt(textField_4.getText());
int lAttend = Integer.parseInt(textField_5.getText());
int tAttend = Integer.parseInt(textField_6.getText());
int wAttend = Integer.parseInt(textField_7.getText());
lh.addStud(moduleName, studId, sFName, sLName , weekNo, lAttend, tAttend, wAttend);
}
else
{
lblNewLabel_4.setText("You have Missing Field");
}
fillDB();
}
});
Below is my query:
String aSQuery = "INSERT INTO Group6_Register VALUES ('" + moduleName + "', '" + studId + "', '" + sFName + "', '" + sLName +"', '" + weekNo + "', '" + lAttend + "', '" + tAttend + "', '" + wAttend + "')";
statements = connection.prepareStatement(aSQuery);
statements.executeUpdate();
"Column count doesn't match value count at row 1"
usually occurs when your columns defined in the values clause don't match your actual table columns.
say your table have 4 coulmns, col1 col2 col3 col4
now you want to only insert data into col2, col3, col4
your insert statement should be
Insert into table (col2, col3, col4) values(col2val, col3val, col3val)
However, i would strongly recommend you to use PreparedStatement while executing sql queries using JDBC.
String query= "Insert into table (col2, col3, col4) Values(?,?,?)";
Statement st = conn.preparedStatement(query);
st.setString(1, col2value);
st.setString(2, col3Val);
st.setString(3, col4Val);
It happens because you are using the implicit type of INSERT statements. The server is expecting that you have provided all values for all columns but you don't that's why it threw an exception.
The best way to do is to explicitly declare the column name for which the values are bound to, ex.
INSERT INTO tableName (colA, colB, colC)
VALUES ('a','b','c')
you can only use this type of syntax when you have all specified values for all columns, for instance, you have a table which has 3 columns, you can then use this
INSERT INTO tableName VALUES ('a','b','c')
Just define the columns you insert explicitly
INSERT INTO table (col1,col2,coln) VALUES ( val1, val2, val3 )
Otherwise you have to set a value for each field

Categories