Hello so i'm trying to code my own type of error catching on a sql statement. On my method add order i want to add some way of stopping someone from selling a product which has no stock. My code below does not yet do that. I can add orders and update the stock amount but i haven't figured out a way of adding an if statement that works.
#FXML
public void AddOrder(ActionEvent event) {
String orderID = orderBox.getText();
String customerID = customerBox.getText();
String productID = productBox.getText();
String amount = amountBox.getText();
// String cost = costBox.getText();
String date = dateBox.getText();
PreparedStatement sample;
dc = new Database();
try {
c = dc.Connect();
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
while (rs.next()) {
Integer amount2 = rs.getInt("Amount");
if (amount2 <= 0) {
System.out.println("No stock exists");
} else {
query = c.prepareStatement(
"INSERT INTO ordertable (orderID,customerID,productID,Amount,Date)VALUES(?,?,?,?,?)");
update = c.prepareStatement("UPDATE inventory set stockAmount = stockAmount-? WHERE productID =?");
update.setString(1, amount);
update.setString(2, productID);
update.execute();
query.setString(1, orderID);
query.setString(2, customerID);
query.setString(3, productID);
query.setString(4, amount);
// query.setString(5, cost);
query.setString(5, date);
query.executeUpdate();
// update.executeUpdate();
Alert confirmation = new Alert(Alert.AlertType.CONFIRMATION, "Saved");
// closeConfirmation.showMessageDialog(this, "Saved");
confirmation.show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
orderBox.clear();
customerBox.clear();
productBox.clear();
amountBox.clear();
dateBox.clear();
loadDataFromDatabase(event);
}
Below is the error i'm getting
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at
If you are just having trouble because of that exception, check these lines:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
ResultSet rs = sample.executeQuery();
The query is defined to accept a parameter for productID, but you haven't given it a value prior to executing the statement. You'll need to change the query so that it doesn't require a parameter or assign a value to the parameter, like this:
sample = c.prepareStatement("Select stockAmount from inventory WHERE productID = ?");
sample.setString(1, productID);
ResultSet rs = sample.executeQuery();
Related
im trying to get the data form this jFrame including the data from the jTable and please consider that the values of the table ( the rows number might change )
I've written this code but its not working and I'm a beginner so please if anyone can help
ive tried this code and no values are being inserted to mysql Table
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.DriverManager");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/StudentAttendence","root","Qjrq3Y3d38");
int rows=jTable1.getRowCount();
for(int row = 0; row<rows; row++)
{
String StudentID = (String)jTable1.getValueAt(row, 0);
String Student_Name = (String) jTable1.getValueAt(row, 1);
String Subject_ = (String)subject.getSelectedItem().toString();
String Date_ = (String)date.getDateFormatString();
Boolean Attendance = (boolean) jTable1.getColumnSelectionAllowed();
String query = "Insert into attendance(StudentID,Student_Name,Subject_,Date_,Attendance) values ('"+StudentID+"','"+Student_Name+"','"+Subject_+"','"+Date_+"','"+Attendance+"')";
pst = con.prepareStatement(query);
pst.execute();
}
JOptionPane.showMessageDialog(null, "Successfully Save");
}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
}
I am running a query on ID column but I don't want it to be visible in my frame/pane. How can I achieve this? Shall I make another table, is there a function in sql/mysql which allows to hide columns? I tried to google it but havent found anything yet.
Here is the code:
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public class ImportData {
Connection connection = TableWithBottomLine.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
connection.setAutoCommit(false);
stmt = connection.createStatement();
stmt.addBatch("update finance.fin set " + stulpPav + " = " + duom
+ " where ID = " + studId + ";");
stmt.executeBatch();
connection.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
connection.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
int rowCount;
Object data [][];
String columnNames [];
public MyTableModel() throws SQLException{
String query ="SELECT ID, tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport, Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
ResultSet rs ;
Connection connection = TableWithBottomLine.getConnection();
Statement stmt = null;
stmt = connection.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][11];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getInt("ID");
data[iEil][1] = rs.getDate("Date");
data[iEil][2] = rs.getFloat("Flat");
data[iEil][3] = rs.getFloat("Mobile");
data[iEil][4] = rs.getFloat("Food");
data[iEil][5] = rs.getFloat("Alcohol");
data[iEil][6] = rs.getFloat("Transport");
data[iEil][7] = rs.getFloat("Outdoor");
data[iEil][8] = rs.getFloat("Pauls_stuff");
data[iEil][9] = rs.getFloat("Income");
data[iEil][10] = rs.getFloat("Stuff");
}
String[] columnName = {"ID", "Date","Flat","Mobile"
,"Food","Alcohol","Transport", "Outdoor", "Pauls_stuff", "Income", "Stuff"};
columnNames = columnName;
}
This has solved my problem:
table.removeColumn(table.getColumnModel().getColumn(0));
I placed this in my class contructor. This lets remove the column from the view of the table but column 'ID' is still contained in the TableModel. I found that many people looking for an option to exclude specific column (like autoincrement) from SELECT statement in sql / mysql but the language itself doesn't have that feature. So I hope this solution will help others as well.
Don't put ID in the select part of the query
String query ="SELECT tbl_Date as Date, Flat, Mobile, Food, Alcohol, Transport,
Outdoor, Pauls_stuff, Income, Stuff FROM finance.fin";
I am trying to return a tuples within a certain year and I can't get the prepared statement to return anything but an empty set. Here is the parameter I call it with: year.valueOf("2014-01-01"); not sure if that's already the problem, and this is just for testing it's normally a value from a textfield.
public List<Sales> findYear(Date date) {
try {
List<Sales> listSales = new ArrayList<>();
I tried it with two parameters so this is just the test version.
When I hard code both dates into the prepared statement it works, so the method itself seems fine. Adding ' ' around the ? makes no difference.
PreparedStatement ps = ConnectDB
.getConnection()
.prepareStatement(
"select * from sales where sale_date between ? and '2014-12-30'");
ps.setDate(1, date);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sales s = new Sales();
s.setEmpno(rs.getInt("empno"));
s.setOutno(rs.getInt("outno"));
s.setPno(rs.getInt("pno"));
s.setCno(rs.getInt("cno"));
s.setOno(rs.getInt("ono"));
s.setQty(rs.getInt("qty"));
s.setSale_date(rs.getDate("sale_date"));
s.setSale_time(rs.getTime("sale_time"));
listSales.add(s);
}
return listSales;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
"select * from sales where sale_date between ?-?-? and ?-?-?"
Then set the dates:
prepare.setInt(1, day1);
prepare.setInt(2, month1);
prepare.setInt(3, year1);
prepare.setInt(4, day2);
prepare.setInt(5, month2);
prepare.setInt(6, year3);
You can also turn a date into a string:
"select * from sales where sale_date between ? and ?"
...
String date1Str = SimpleDateFormat("dd-MM-yyyy").format(date1);
String date2Str = SimpleDateFormat("dd-MM-yyyy").format(date2);
prepare.setString(1, date1Str);
prepare.setString(2, date2Str);
Expanded example:
try {
PreparedStatement ps = ConnectDB.getConnection()
.prepareStatement(
"select * from sales where sale_date between ? and ?");
ps.setDate(1, date);
// whatever date2 is
ps.setDate(2, date2);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sales s = new Sales();
s.setEmpno(rs.getInt("empno"));
s.setOutno(rs.getInt("outno"));
s.setPno(rs.getInt("pno"));
s.setCno(rs.getInt("cno"));
s.setOno(rs.getInt("ono"));
s.setQty(rs.getInt("qty"));
s.setSale_date(rs.getDate("sale_date"));
s.setSale_time(rs.getTime("sale_time"));
listSales.add(s);
}
return listSales;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).
I am trying to create a simple little webservice on a glassfish server backed by a mysql server on my netbeans
Its designed to be a very simple currency conversion service
Here is what its supposed to do
It takes an amount of money (Always in GBp) as an INT and a currency to convert it in as a string.
The service then looks up that currency from my database table to get the conversion rate with a query like
select * from exchange.rates where currency = string
Then it performs the simple calculation to convert the money into the currency and returns the amount
The problem is that i have no clue how to call that conversion rate from my mysql server, i tried and tried but nothing happens
i just keep getting the same amount i entered in.
I tried entering euro and 10
I set the rate for that in my database but i just got 10 back out when i tested the webservice
/**
* Web service operation
*/
#WebMethod(operationName = "convert")
public int convert(#WebParam(name = "currency") String currency, #WebParam(name = "amount") int amount) {
int newamount = 0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/exhange",
"root", "25587");
PreparedStatement st =
con.prepareStatement("select * from rates where currency = '" + currency+"'");
ResultSet rs = null;
rs = st.executeQuery();
rs.first();
newamount =rs.getInt("conversion") * amount;
return newamount;
} catch (Exception e) {
System.out.println("error");
}
return amount;
}
Whe you use prepared statemen you need to pass the parameter explicitly:
PreparedStatement st = con.prepareStatement("select * from rates where currency = ?");
st.setString(1,currency) //Check this
ResultSet rs = st.executeQuery();
// If you are sure that is only one row then you nee to do
String columnX = null;
if (rs.next() != null) {
columnX = rs.getString(1); //Where 1 is the first column
}