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);
}
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;
}
}
Im receiving a number of different errors when trying to insert products into my access DB. Such as Malformed String: ). User lacks privilege or object cant be found. Different errors when i try and insert different products.
tried re creating the db, debugging to the hilt.
public boolean addNewProduct(Product product)
{
String Make = "";
String Model = "";
String Type = "";
String Genre = "";
String AttConsole = "";
String Desc = "";
if(product.getClass().getName().equals("Models.Game"))
{
Game game = (Game)product;
Genre = String.valueOf(game.getGenre());
AttConsole = String.valueOf(game.getAttributedConsole());
Desc = String.valueOf(game.getDescription());
}
else if(product.getClass().getName().equals("Models.Console"))
{
Console console = (Console)product;
Make = String.valueOf(console.getMake());
Model = String.valueOf(console.getModel());
Desc = String.valueOf(console.getDescription());
}
else
{
Peripheral peripheral = (Peripheral)product;
Type = String.valueOf(peripheral.getType());
Desc = String.valueOf(peripheral.getDescription());
}
try
{
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionString);
Statement stmt = conn.createStatement();
stmt.executeUpdate("INSERT INTO Products (ProductName, Price, StockLevel, Description, Genre, AttributedConsole, Make, Model, Type) VALUES "
+ "('" + product.getProductName() + "','" + product.getPrice() + "','" + product.getStocklevel()
+ "','" + Desc + "','" + Genre + "','" + AttConsole +
"','" + Make + "','" + Model + "'," + Type + ")");
//sql statement to add new products to database
conn.close();
return true;
}
catch(Exception ex)
{
String message = ex.getMessage();
return false;
}
}
ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 unexpected token: )
ex = (net.ucanaccess.jdbc.UcanaccessSQLException) net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::4.0.4 user lacks privilege or object not found: RAZOR
Don't use string concatenation to insert column values into SQL command text. Search for "SQL Injection" or "Little Bobby Tables" for more information on why that is a "Bad Thing"™.
Instead, use a PreparedStatement to run a parameterized query, e.g.,
String sql = "INSERT INTO tableName (intColumn, textColumn) VALUES (?, ?)";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
ps.setInt(1, 12345);
ps.setString(2, "my text value");
ps.executeUpdate();
}
I have a JDBC program that takes records from a MySQL database and prints out the results. The user can select which results they want from the database by selecting different checkboxes to only display certain results.
Here is the method which gets the records and prints them out:
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
result += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
result += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
result += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
result += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
result += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
result += zip + " ";
}
// print the results
}
System.out.println(result);
results.setText(result);
stmt.close();
}
Currently, if I were to select say the first three checkboxes, I would get the output:
1 Smith, Tim 12 Elm St 2 Jones, Tom 435 Oak Dr 3 Avery, Bill 623 Ash Ave 4 Kerr, Debra 1573 Yew Crt
However, the output I am after is:
1, Smith, Tim, 12 Elm St
2, Jones, Tom, 435 Oak Dr
3, Avery, Bill, 623 Ash Ave
4, Kerr, Debra, 1573 Yew Crt
Is there any way I can add a new line after each record in the database, as well as maybe the commas in between items in each record? I am new to JDBC and MySQL connectivity, so any help or tips is appreciated.
You can print every single result just before the end of while loop, then it'll print every record in new line.
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
String result = "";
String singleResult = "";
while (rs.next()) {
if (cb1.isSelected()) {
int custid = rs.getInt("custid");
singleResult += custid + " ";
}
if (cb2.isSelected()) {
String name = rs.getString("name");
singleResult += name + " ";
}
if (cb3.isSelected()) {
String address = rs.getString("address");
singleResult += address + " ";
}
if (cb4.isSelected()) {
String city = rs.getString("city");
singleResult += city + " ";
}
if (cb5.isSelected()) {
String state = rs.getString("state");
singleResult += state + " ";
}
if (cb6.isSelected()) {
int zip = rs.getInt("zip");
singleResult += zip + " ";
}
System.out.println(singleResult);
result +=singleResult;
}
//System.out.println(result);
results.setText(result);
stmt.close();
}
Or you can append line separator, just before closing while loop
System.out.println(singleResult);
result +=singleResult;
result +="\n";
First, I would use a StringJoiner to gather the elements. Then, I would eliminate the many local temporary variables. Finally, I would use println in the loop and another StringJoiner for the final result. Like,
private void execute() throws SQLException {
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
StringJoiner result = new StringJoiner(System.lineSeparator());
while (rs.next()) {
StringJoiner lineJoiner = new StringJoiner(", ");
if (cb1.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
lineJoiner.add(rs.getString("name"));
}
if (cb3.isSelected()) {
lineJoiner.add(rs.getString("address"));
}
if (cb4.isSelected()) {
lineJoiner.add(rs.getString("city"));
}
if (cb5.isSelected()) {
lineJoiner.add(rs.getString("state"));
}
if (cb6.isSelected()) {
lineJoiner.add(String.valueOf(rs.getInt("zip")));
}
System.out.println(lineJoiner);
result.add(lineJoiner.toString());
}
results.setText(result.toString());
stmt.close();
}
You could also do the same thing with Collection(s) like,
String query = "SELECT * FROM customers";
ResultSet rs = stmt.executeQuery(query);
List<String> msg = new ArrayList<>();
while (rs.next()) {
List<String> al = new ArrayList<>();
if (cb1.isSelected()) {
al.add(String.valueOf(rs.getInt("custid")));
}
if (cb2.isSelected()) {
al.add(rs.getString("name"));
}
if (cb3.isSelected()) {
al.add(rs.getString("address"));
}
if (cb4.isSelected()) {
al.add(rs.getString("city"));
}
if (cb5.isSelected()) {
al.add(rs.getString("state"));
}
if (cb6.isSelected()) {
al.add(String.valueOf(rs.getInt("zip")));
}
String line = al.stream().collect(Collectors.joining(", "));
System.out.println(line);
msg.add(line);
}
results.setText(msg.stream().collect(Collectors.joining(System.lineSeparator())));
stmt.close();
Prefer whichever you find most readable.
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.
Here is sample code ...
Statement stmt = con.createStatement();
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println(query); // displaying only `
ResultSet rs = stmt.executeQuery(query);
System.out.println(query);
while (rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
If String passed Instead of passing variable then it works ...like
ResultSet rs = stmt.executeQuery("select * from work_product where product_name ='product' ");
I also used preparedStatement...but not working ...
PreparedStatement statement = con.prepareStatement("select * from work_thing_db.work_product where product_name = ? ");
statement.setString(1,ch);
Here is full code ....
#FXML protected void keyReleased(KeyEvent evt)throws Exception {
//SetTimer();
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
}
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Using : IntelliJ IDEA 14 CEOutput :
Enter key Fired
product
In dbSearch
Concat String :product
'
kindly point out my mistake ... i'm new in java... and further i need to use like and or with it .... please provide answer with explanation... Thanks in advance.
It's possible there is no match in the data. You could run a non filtered query first and see what values you have for product_name in the table.
I haven't thought of it....
private void dbSearch(String ch){
System.out.println("In dbSearch");
System.out.println("Concate String :"+ch);
ch = ch.trim().toString(); // trim and type cast ... its working
String query = "select * from work_product where product_name ='" + ch + "' ";
System.out.println("Query is :"+query);
dbConnector conn = new dbConnector();
Connection con = conn.dbConnection();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
System.out.println(rs.getString(1)+" "+rs.getString(2));
}
}catch(Exception e){System.out.println(e);}
}
Now it is fetching data properly ...
There is something wrong in the way you concatenate the string
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
concateString = concateString + ch; //concateString has scope
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
}
}
so when the user will enter "ENTER" (can be \n or \r) you will concatenate before the condition of the key value so concateString will always contain your string + "ENTER" (i.e. the carriage return). Thats the reason you only get the quote when you print your query
Not to modify much of your code, you can do
if (evt.getCode() != KeyCode.BACK_SPACE) {
String ch = evt.getText();
//runThread();
if (evt.getCode() == KeyCode.ENTER) {
System.out.println("Enter Key Fired ");
System.out.println(concateString);
dbSearch(concateString);
} else {
concateString = concateString + ch; //concateString has scope
}
}
and so you will pass the correct string