I want to multiple price and quantity, so i can get the total, and put it in the table too. Can you help me? Because I already search other reference and add public Object getValueAt(int row, int column) {} but I got error so I delete it -_-
try {
String trans_id = txtNo.getText();
String menu_id = txtMID.getText();
String quantity = txtQuan.getText();
String menu_price = "";
Statement stmt;
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM menu");
stmt.executeUpdate("insert into transaction (trans_id, menu_id, menu_price, quantity)"
+ "values ('" + trans_id + "','" + menu_id + "','" + menu_price + "','" + quantity + "')");
DefaultTableModel model = (DefaultTableModel) tblMenu.getModel();
if (rs.next()) {
txtNo.setText("" + rs.getString("trans_id"));
txtMID.setText("" + rs.getString("menu_id"));
menu_price = rs.getString("menu_price");
txtQuan.setText("" + rs.getString("quantity"));
model.addRow(new Object[]{trans_id, menu_id, menu_price, quantity});
}
} catch (Exception e) {
System.out.println("Failed" + e);
}
Really need your help.
You'll have to first convert price and quantity to numerical values, multiply them, and then convert the product back to a String. You can convert the text values of price and quantity using Integer.parseInt(String s). Or Double.parseDouble if your price is not an integer...you get the idea. Do that for both price string and quantity string. Then you can get the String value by String.valueOf(whatever your price * quantity value is), assuming you want to put that value into the table as a String.
Related
i am trying to enter the city name if city name is exist in database (else error message), then i want to print selected city name, population, latitude and longitude. Rest of the code is working well.
Database image is here
public static void city(){
ResultSet rs = null;
Scanner k = new Scanner (System.in);
System.out.println("Enter the name");
String Name = k.nextLine ();
try {
rs = stmt.executeQuery("SELECT * FROM cities WHERE name ="+Name);
// At least a record selected
if(rs.isBeforeFirst ()){
//Iterates through each record
while (rs.next ()){
String name = rs.getString (i:1);
int population = rs.getInt(i:2);
double latitude = rs.getDouble (i:3);
double longitude = rs.getDouble(i:4);
System.out.println("Name: " + name);
System.out.println("Population: " + population);
System.out.println("Latitude: " + latitude);
System.out.println("Longitude: " + longitude);
System.out.println();
}
}
else {
System.out.println("No records selected.");
}
}
catch(SQLException e) {
System.out.println("Error selecting from table: " + e.getMessage());
}
finally {
try {
rs.close();
}
catch(Exception e) {
//ResultSet still null/nothing to close
}
}
}
First if field "name" is character varying or text, you must modify your 8th line like this:
rs = stmt.executeQuery("SELECT * FROM cities WHERE name ='"+Name+"'");
This will check whether there is city name in your database
rs = stmt.executeQuery("SELECT * FROM cities WHERE name = '"+name+"'");
if(rs.next()){
//it exist
//print record
}
else{
//it does not exist
System.out.println("Error Message!");
}
You can also use PreparedStatement for your query instead of the above query.
PreparedStatement p = yourConnection.prepareStatement("SELECT * FROM cities WHERE name = ?");
p.setString(1, name);
rs = p.executeQuery();
Looks like it's missing quotes, try this:
rs = stmt.executeQuery("SELECT * FROM cities WHERE name = '"+Name+"' ");
So, I have something like this:
System.out.println("Enter owner's IC no. or plate no. : ");
String update = in.nextLine();
String sql = String.format("SELECT * FROM `vehicle` WHERE ic='%s' OR plate ='%s'",update,update);
ResultSet rs = stmt.executeQuery(sql);
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
while (rs.next()) {
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(toString());
}
What I'm trying to do is, if data is found in the database, it will then print the following table for outputs that match.
Now, It is supposed to print out every output. But, it only prints out the first one.
I believe that the following code is the cause:
if(rs.next()) {
System.out.println("RegNo." +"\t\t"+ "Name" + "\t\t" + "IC" +"\t\t" + "Plate No." + "\t" + "Color" + "\t\t" + "Year" + "\t\t" + "Make" + "\t\t" + "Model" +"\t\t"+ "Capacity" + "\t" + "Type" +"\t\t" + "Max Load");
}
else {
System.out.println("IC and PLate No. not found....");}
I also faced the same problem, when used select query with Prepared statement.
For example-
String sqlquerySELECTAgentsWithParam = " select * from AGENTS WHERE AGENT_CODE = ( ? ) ";
it returned a single row, since I've used IF condition and then while(rs.next())
I couldn't print the single row, Hence, I've used do-while loop like below in order to print the first-row result. code snippet below- hope it will help !!
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection(oracelDBUrl, oracleDBUser,oracleDBPwd );
if (conn != null) { System.out.println("Connected to the Oracle DB "); }
else { System.out.println("Failed to Connect to Oracle DB "); }
PreparedStatement pstmt = conn.prepareStatement(sqlquerySELECTAgentsWithParam);
pstmt.setString(1,"<agent_id>");
ResultSet rs = pstmt.executeQuery();
boolean returnResultrs = rs.next();
System.out.println("Fetched Result is = " +returnResultrs);
if(returnResultrs)
{
do {
System.out.println("Inside Do - While Loop");
System.out.println("AGENT_CODE = " + rs.getString(1)+ "has AGENT_NAME = " +rs.getString(2));
}
while(rs.next());
}
Use MessageFormat to format the output, and the counter to determine if empty result set, like so:
String strFormat = "RegNo. {0}\tName {1}\tIC {2}\tPlate No. {3}\tColor {4}\tYear {5}\tMake {6}\tModel {7}\tCapacity {8}\tType {9}\tMax Load {10}");
int counter = 0;
while (rs.next()) {
counter++;
regno = rs.getInt("regno");
name = rs.getString("name");
ic = rs.getString("ic");
plate = rs.getString("plate");
color = rs.getString("color");
year = rs.getInt("year");
make = rs.getString("make");
model = rs.getString("model");
capacity = rs.getDouble("capacity");
type = rs.getString("type");
maxload = rs.getDouble("maxload");
System.out.println(MessageFormat.format(strFormat, regno, name, ic, plate, color, year, make, model, capacity, type, maxload));
}
if (counter == 0) {
System.out.println("IC and PLate No. not found....");
}
So I see two issues here. The biggest one is this:
System.out.println(toString());
That calls the .toString() method on the current class, which will not output any of the data from your ResultSet. At least, not based on any of the code you've shown. You're storing all of the values coming back from the ResultSet in variables, but those variables don't appear to be getting used anywhere. You need to get those variables to your .println() somehow.
The second issue is that rs.next() moves the cursor forward one row. So when you do this:
if(rs.next()) {
That causes you to skip the first row. This is actually kind of tricky to fix, because there's no good way to tell whether or not a ResultSet is empty without calling .next(). The way I'd probably handle this is to pull all of the results into objects in a list, and then do all the printing based on the list, and not on the ResultSet itself.
This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'
I have two method one is working and other's not working for insert query
// this one fails
public void product(String product, String quantity, String price,
String date) throws SQLException {
try {
statement.execute("INSERT INTO product (productn,quantity,price,date) VALUES ('" + product + "','" + quantity + "','" + price + "','" + date + "')");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// this one works
public void customer(String name, String q, String p, String pro)
throws SQLException {
try {
statement.execute("INSERT INTO Customer (name,price,product,quantity) VALUES ('" + name + "','" + q + "','" + p + "','" + pro + "')");
} catch (Exception e) {
System.out.println("problem in Customer insert !");
}
}
one method which is working fine mean it insert data into the table but the other is giving the following error:
[Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement
Try this:
INSERT INTO product ([productn],[quantity],[price],[date]) VALUES ('" + product + "','" + quantity + "','" + price + "','" + date + "')
And let me know if it works
You'll have more chance to do it in this way, like that you could check better the integrity of the values.
private static final String insert = "INSERT INTO product (productn,quantity,price,date) VALUES ('"+?+"','"+?+"','"+?+"','"+?+"')";
statement.clearParameters();
statement.set"Type_of_the_value"(1, productn) ;
statement.set"Type_of_the_value"(2, quantity) ;
statement.set"Type_of_the_value"(3, price) ;
statement.set"Type_of_the_value"(4, date) ;
statement.executeUpdate() ;
I have a problem when I try to execute my query in Java. when I try to add an object to my database in SQL, it gives me a error saying that the instruction don't send the result set. When I execute the query in sql server, it work fine and it insert the object. Please help me.
public void addAlbum(String title, double price, String genre, String date, String home, String image) {
int number = getData().size();
boolean isThere = false;
Statement statement;
for(int i = 0; i < getData().size();i++){
if(getData().get(i).getTitle().equals(title)){
isThere = true;
}
}
if(!isThere){
try{
statement = connexion.createStatement();
String query = "use albums INSERT INTO dbo.Album(Album.artist_number, title, price, genre, date, home, image) VALUES(" + number + ", '" + title + "', " + price + ", '" + genre + "', '" + date + "', '" + home + "', '" + image + "')";
statement.executeQuery(query);
getData().add(new Album(String.valueOf(number),title, price, genre, date, home));
fireTableRowsInserted(getData().size() -1, getData().size() -1);
}catch(SQLException e){
JOptionPane.showMessageDialog(null,
"Error "
+ e.getMessage(), "Result",
JOptionPane.ERROR_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null,
"There is already an album with this name", "Result",
JOptionPane.ERROR_MESSAGE);
}
}
You need to use Statement.executeUpdate(String) for INSERT. Statement.executeQuery(String) is for SELECT.
PreparedStatements are better, easier and safer. Using Prepared Statements.