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;
}
}
Related
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 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);
}
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.
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;
}