JAVA - MySQL an ArrayList - java

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.

Related

How do I value a label using a database information?

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;
}
}

How to concatenate Resultset to String variable

I want to get my ItemName columns value to one String separate from commas.
I tried like this.but its not working
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '"+invoicenum+"' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
while (rs.next()) {
String em = rs.getString("ItemName");
description = em.replace("\n", ",");
System.out.println(description);
}
You should change to this, if you want to do the concatenation in java:
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
while (rs.next()) {
description += rs.getString("ItemName") + ",";
}
description = description.substring(0, description.length() - 1);
//System.out.println(description);
}
If you want to concatenate in query then you could search for GROUP_CONCAT() function
String sql = "SELECT `ItemName` FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
StringBuilder builder = new StringBuilder(); // used to store string and append data further if you want
while (rs.next()) {
builder.append(rs.getString("ItemName").append(","); // adding data/Item name to builder and appending comma after adding item name
}
if(builder.length() > 0){ // if there's some data inside builder
builder.setLength(builder.length() - 1); // remove last appended comma from builder
}
System.out.println("Command Separated Data" + builder.toString()); // final data of item name
}
Other way is to concate result from SQL itself.(here's a MySQL compatible code)
String sql = "SELECT group_concat(`ItemName`) as items FROM `invoicelist` WHERE `InvoiceId` = '" + invoicenum + "' ";
try {
ResultSet rs = CODE.DbAccess.getdata(sql);
String data = "";
while (rs.next()) {
data = rs.getString("items")
}
System.out.println("Command Separated Data" + data);
}

Best way to print data from two columns of mySQL database to jTextfield one after another

I am trying to make a program in which i read an input from the user i.e. in the textfield named gname and store its value to a string called grammar. Now this input is what sorts my output from the database.
Database looks like this
So when user enters G1 in the textfield it should display records in such a way
A->ab,A-ab,B->b
But it only shows 1st element when i use if(myRs.next) and last one if i use while(myRs.next().
current output is
Here is the code for this:
its all in try catch block
String grammar = gname.getText();
myCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/grammar", "root", "");
JOptionPane.showMessageDialog(rootPane, "Connected to database");
mystmt = myCon.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String query = "SELECT starting_symbol, value from starting_symbol where grammar= '" + grammar + "'";
String query2 = "SELECT non_terminals, terminals from input_values where grammar= '" + grammar + "'";
mystmt.addBatch(query);
mystmt.addBatch(query2);
myCon.setAutoCommit(false);
mystmt.addBatch(query);
mystmt.addBatch(query2);
myRs = mystmt.executeQuery(query);
while (myRs.next()) {
String s = myRs.getString("starting_symbol");
String val = myRs.getString("value");
output.setText(s + "-> " + val);
}
myRs = mystmt.executeQuery(query2);
ArrayList<String> list_one = new ArrayList<String>();
ArrayList<String> list_two = new ArrayList<String>();
while (myRs.next()) {
list_one.add(myRs.getString("non_terminals"));
list_two.add(myRs.getString("terminals"));
for (int i = 0; i < list_one.size(); i++) {
output_2.setText(list_one.get(i) + "->" + list_two.get(i));
}
}
Please help me in getting the correct outut
Use StringBuilder Luke
StringBuilder b = new StringBuilder();
while (myRs.next()) {
String s = myRs.getString("starting_symbol");
String val = myRs.getString("value");
if (b.length() > 0) {
b.append(',');
}
b.append(s + "-> " + val);
}
output.setText(b.toString());
And do the same for output_2 field
Your code snippet can be just like the following:
StringBuilder sb = new StringBuilder();
while (myRs.next()) {
if (sb.length() > 0) sb.append(",");
sb.append(myRs.getString("non_terminals"))
.append("->")
.append(myRs.getString("terminals"));
}
Instead of calling output_2.setText multiple times that only set the text to be the last fetch value of non_terminals -> terminals in this case B->b.

Before start of result set running multiple sql

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.

MySQLSyntaxErrorException when setting strings

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

Categories