I'm currently working on an application for a restaurant. The idea for the code I'm currently working on is that it gets the name from a combobox and inserts a receipt into the database whith the employee number of the person who is working on it. The code whith which I'm trying to do it is:
RestaurantOrder sqlRestaurantOrder = new RestaurantOrder();
ActionListener printReceiptListner;
printReceiptListner = (ActionEvent) -> {
int ID = Integer.parseInt(input1.getText());
try {
SystemManager manager = new SystemManager();
ResultSet rs = manager.stmt.executeQuery(sqlRestaurantOrder.setIdSql(ID));
while (rs.next()) {
double totalPrice = rs.getDouble("sumprice");
if (ID > 0) {
Receipt receiptSql = new Receipt();
String firstName = (String) cb.getSelectedItem();
String checkoutDate = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
ResultSet rs2 = manager.stmt.executeQuery(receiptSql.getEmployeeId(firstName));
int employeeId = rs2.getInt("id");
while (rs2.next()) {
Receipt receiptSql2 = new Receipt();
ResultSet rs3 = manager.stmt.executeQuery(receiptSql2.SetStatusReceipt(employeeId, checkoutDate, ID, totalPrice));
while (rs3.next()) {
}
}
}
}
} catch (SQLException k) {
JOptionPane.showMessageDialog(null, k.getMessage());
}
};
The statements are:
public class Receipt {
public String sql;
public String sql2;
public String getEmployeeId(String firstName){
return sql2 = "SELECT id FROM employee WHERE firstName = '" + firstName + "';";
}
public String SetStatusReceipt(int employeeId, String checkoutDate, int id, double totalPrice){
return sql = "INSERT INTO `receipt` (`employeeId`, `price`, `restaurantOrderId`, `checkoutDate`) VALUES (" + employeeId + " , " + totalPrice + ", " + id + ", " + checkoutDate + ");";
};
}
I'm getting the error before start of result set which I looked up what it means but I can't get it fixed at the moment. Help will be appreciated.
If I forgot to post more important code let me know I'll update it
You have to call ResultSet.next() before you are able to access the fields of that ResultSet. So you need to move your assignment of employeeId into your while loop:
while (rs2.next()) {
int employeeId = rs2.getInt("id");
From the documentation of ResultSet.next():
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
Related
I want to display the information in a database table using multiple labels.
This information for each person is unique and pertains to each row in the table.
After logging in to the program, each person should be able to see their information and correct it if they want, by logging in to their profile page.
For each column of the table, I have provided a label, which displays the information of each person based on the column.
I wrote the following code to display the database data on the label, but when I run it, nothing is displayed!
I also do not know whether to use ResultSet and its methods or Statement and its methods to get the string to use in Label.
enter code here
private void displayProfileDetails(String resultSetQuery, Label label) {
DatabaseConnection connectToDrugDatabase = new DatabaseConnection();
try (
Connection connectionDB = connectToDrugDatabase.getConnection();
Statement statement = connectionDB.createStatement();
ResultSet resultSet = statement.executeQuery(resultSetQuery);) {
while (resultSet.next()) {
label Text
if (resultSet.next()) {
baseMessageLabel
Platform.runLater(() -> {
label.setText(resultSet.toString());
}
);
} else {
label.setText("null");
}
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
}
private void profileDetails() {
String firstNameDisplayQuery = "SELECT * FROM APP.users WHERE USERNAME = '" + userID + "'";
String lastNameDisplayQuery = "SELECT * FROM APP.users WHERE FIRSTNAME = '" + userID + "'";
String userNameDisplayQuery = "SELECT * FROM APP.users WHERE LASTNAME = '" + userID + "'";
String passwordDisplayQuery = "SELECT * FROM APP.users WHERE PASSWORD = '" + userID + "'";
String EmailDisplayQuery = "SELECT * FROM APP.users WHERE PHONENUMBER = '" + userID + "'";
String AddressDisplayQuery = "SELECT * FROM APP.users WHERE ADDRESS = '" + userID + "'";
String phoneNumberDisplayQuery = "SELECT * FROM APP.users WHERE JOB = '" + userID + "'";
String jobDisplayQuery = "SELECT * FROM APP.users WHERE EMAIL = '" + userID + "'";
displayProfileDetails(firstNameDisplayQuery, firstNameLabel);
displayProfileDetails(lastNameDisplayQuery, lastNameLabel);
displayProfileDetails(userNameDisplayQuery, userNameLabel);
displayProfileDetails(EmailDisplayQuery, emailLabel);
displayProfileDetails(AddressDisplayQuery, addressLabel);
displayProfileDetails(phoneNumberDisplayQuery, phoneNumberLabel);
displayProfileDetails(jobDisplayQuery, JobLabel);
displayProfileDetails(passwordDisplayQuery, passwordLabel);
}
When you call resultSet.next() you moved the cursor ahead.
Then you called resultSet.next() again in an if statement and moved it ahead again without getting the value from the first record;
Remove the if statement because if the while loop is running, there is a valid record at the cursor already.
Also resultSet.toString() won't populate the field with your data. You need to use rs.getString(index); where index is the column index (starts at 1) of the column you just got.
Here is an example of what you could do.
// this method returns all columns of a row in ordinal() order. If username is the first column of your table then object[0] will contain a String with that data. etc.
private Object[] getUserDataByUserName(Connection conn, String username) throws SQLException {
try (PreparedStatement ps = conn.prepareStatement("select * from APP.USER where username = ?")) {
ps.setString(1, username);
try (ResultSet results = ps.executeQuery()) {
if (results.next()) {
Object[] row = new Object[results.getMetaData().getColumnCount()];
for (int i = 0; i < row.length; i++) {
// arrays start at pos 0, but result sets start at column 1
row[i] = results.getObject(i + 1);
}
return row;
}
}
return null;
}
}
I have query from MySQl
String sqlSearch = "SELECT * from Item"
and method with ArrayList
public static ArrayList<String> checkNo() throws SQLException {
ArrayList<String> no= new ArrayList<String>();
DbManager db = new DbManager();
db.connect();
String sql = "SELECT * from Category where id = " + idUser + " ";
Statement stmt = db.connect().createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
no.add(rs.getString("nameCategory"));
}
db.disconnect();
return no;
}
And I get from specific user his category in arraylist, but how to pass this category to sqlSearch???
SELECT * from Item where category ????
data from ArrayList
Any idea?
You could loop through the ArrayList items and build a String to use in the where clause like this
String inCondition = "";
boolean first = true;
ArrayList<String> categories = checkNo();
for(String cat : categories){
if(first){
first = false;
} else {
inCondition += ",";
}
inCondition += cat;
}
String sqlSearch = "SELECT * from Item where category in (" + inCondition + ")";
Your checkNo() method return an ArrayList. It looks like this ArrayList will have only one item, get that item from the ArrayList and pass it to the query like this.
String category = list.get(i);
"Select * from Item where category = "+category;
As your query is not clear am giving you a sample code,jus try it
if (count > 0) {
for (int i = 0; i < count; i++) {
ColumnName= no.get(i).getColumnName();
}
getItemQuery = "FROM Item where category in (" +ColumnName + ")";
}
There are many ways of doing this,
one way is two combine two queries:
SELECT * from Item where category in (SELECT nameCategory from Category where id = idUser )
as suggested its better to use prepared statement.
I have a strange problem. When I execute the query in the following piece of code it throws a MySQLSyntaxErrorException with the message:
You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near
''fantasy' SET Quantity = 3 WHERE BookName = 'The Silmarilion'' at line 1
Code:
private void updateDBTable(String category, Vector dataVector) {
try {
for(int i = 0; i < dataVector.size(); i++) {
String bookName = String.valueOf(((Vector) dataVector.elementAt(i))
.elementAt(0));
int quantity = (int) ((Vector) dataVector.elementAt(i))
.elementAt(4);
statement = databaseConnection
.prepareStatement("UPDATE ? SET Quantity = ? WHERE BookName = ?");
statement.setString(1, category);
statement.setInt(2, quantity);
statement.setString(3, bookName);
statement.executeUpdate();
}
}
But if I write it in this way :
private void updateDBTable(String category, Vector dataVector) {
try {
for(int i = 0; i < dataVector.size(); i++) {
String bookName = String.valueOf(((Vector) dataVector.elementAt(i))
.elementAt(0));
bookName = "'" + bookName + "'";
int quantity = (int) ((Vector) dataVector.elementAt(i))
.elementAt(4);
statement = databaseConnection
.prepareStatement("UPDATE " +
category +
" SET Quantity = ? WHERE BookName = " +
bookName);
statement.setInt(1, quantity);
statement.executeUpdate();
}
}
It works fine. Can you help me to figure out why the syntax in the first example is wrong?
In the first case, you have also provided the table name as a parameter. Prepared statements take the column names as parameters. You need to provide the table name in the statement while using prepareStatement
Hi guys can u tell me what is wrong with my code?
When I set my ResultSet as "SELECT * FROM Table1" it works perfectly,
also if it is "SELECT key, itemName, itemPrice, itemQuantity FROM Table1"
but when I try to use only one of them or two it prints out an error column not found.
My database is stored in MS Acceess. That's my main:
try (Connection cn = DBUtil.getConnection(DBType.MS_ACCESS);
Statement st = cn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = st.executeQuery("SELECT Table1.key FROM Table1");) {
Table1.displayData(rs);
} catch (SQLException ex) {
DBUtil.processException(ex);
}
and that's Table1.java:
public class Table1 {
public static void displayData(ResultSet rs) throws SQLException {
// to print out my database
while (rs.next()) {
StringBuffer buffer = new StringBuffer();
buffer.append(rs.getString("key") + " ");
buffer.append(rs.getString("itemName") + " ");
double price = rs.getDouble("itemPrice");
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
String formattedPrice = pounds.format(price);
buffer.append(formattedPrice + " ");
buffer.append(rs.getInt("itemQuantity") + " ");
System.out.println(buffer.toString());
}
}
}
Your result set will only contain the columns that you define in your select query. So if you do
rs.getString("itemName")
then you have to select that column in your query, which you don't
st.executeQuery("SELECT Table1.key FROM Table1")
^-----------------column missing
Do
st.executeQuery("select key, itemName, itemPrice, itemQuantity from Table1")
you should use
buffer.append(rs.getString("Table1.key") + " ");
resultset have the data with name which you have given in select query.(key=Table1.key)
I'm using MySQL commands via JDBC (Java) to make changes to my database. I have implemented the following method to return the values of a column. The goal is to have the location in the column (row) correspond with their location in the array (index). This works with String columns, but with numerical columns, the ResultSet seems to place them in ascending order, thus making their positioning in the returned String array not reflect their positioning in the column. 'rs' is a ResultSet reference variable.
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName;
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}
It's as simple as adding an ORDER BY clause to the SQL command. Here's my working method:
public String[] getColumnContents(String tableName, String columnName) {
String sql = "SELECT " + columnName + " FROM " + tableName + " ORDER BY " + columnName1 + " ASC, " + columnName2 + " ASC";
String[] results = new String[SQLManager.getColumnLength(tableName, columnName)];
try {
rs = statement.executeQuery(sql);
for (int counter = 0; rs.next(); counter++) {
results[counter] = rs.getString(columnName);
}
} catch (SQLException e) {
e.printStackTrace();
}
return results;
}