Populating jTable from postgresql - java

I am doing java project in NetBeans 8 using databases and GUI.The problem is appearing when I search through the database and add the found values to JTable: all values are being added only to first column of JTable while I need them added separately to corresponding columns. I tried getColumnCount() and it also gave me 1 meaning that I have only one column. How to add database values to JTable's corresponding columns?
I've tried all the populating functions adviced here
My code:
jTable1 = new javax.swing.JTable();
String sql = "SELECT (flight_id, plane_name, dep_city, arival_city, date_month, date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats) FROM flight "
+ "WHERE (dep_city = '" + SearchFlight.getFromCity() + "' AND "
+ "arival_city = '" + SearchFlight.getToCity() + "' AND "
+ "date_month = '" + SearchFlight.getMonth() + "');";
PreparedStatement stat = conn.prepareStatement(sql);
ResultSet rs = stat.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs)
);
jScrollPane1.setViewportView(jTable1);
SearchFlight is a GUI class, and its methods return strings obtained in GUI.
DbUtils.resultSetToTableModel(rs)is a method in net.proteanit.sql.DbUtils;
So, it is expected that the data will be filled into 9 columns, hoewever it fills all the data into one column.

SELECT ( ... )
must be
SELECT ....
And better use the PreparedStatement as intended. Otherwise SQL injection still is possible. And try-with-resources closes the things under all circumstances.
String sql = "SELECT flight_id, plane_name, dep_city, arival_city, date_month, "
+ "date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats "
+ "FROM flight "
+ "WHERE dep_city = ? AND "
+ "arival_city = ? AND "
+ "date_month = ?";
try (PreparedStatement stat = conn.prepareStatement(sql)) {
stat.setString(1, SearchFlight.getFromCity());
stat.setString(2, SearchFlight.getToCity());
stat.setString(3, SearchFlight.getMonth());
try (ResultSet rs = stat.executeQuery()) {
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
}

Related

Prepared Statement in Java/SQL Server not returning any results

List<Guest> guestList = new ArrayList<>();
String query = "select * from Guests where ? like ?";
System.out.println("select * from Guests where " + property + " like '%" + value + "%'");
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1, property);
preparedStatement.setString(2, "'%" + value + "%'");
ResultSet resultSet = preparedStatement.executeQuery();
guestList = getGuestListFromResultSet(resultSet);
return guestList;
As you can see above, I created a Prepared Statement, which is later populated with 2 values: property and value. Running the above query should give me some results in SQL Server.
I also tried these variations for setting the second parameter(value):
preparedStatement.setString(2, "%" + value + "%");
preparedStatement.setString(2, value);
None of these seem to work. What does work is simply building the query from string concatenation:
PreparedStatement preparedStatement = connection.prepareStatement("select * from Guests where " + property + " like '" + value + "'");
However, I want to use a Prepared Statement.
You can't use a variable as a column name. Instead, you can use dynamic SQL
String query = """
DECLARE #sql nvarchar(max) = '
select *
from Guests
where ' + QUOTENAME(?) + ' like #value;
';
EXEC sp_executesql #sql,
N'#value nvarchar(100)',
#value = ?;
""";
Note the use of QUOTENAME to correctly escape the column name.
Note also the use of sp_executesql to pass the value all the way through.
I'm not sure about the JDBC driver, but ideally you should use proper named parameters, rather than ?

SQL database update statement not working

ResultSet rs = stat.executeQuery("select * from donor where username = '" + username + "'");
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
System.out.println(Updatesentence);
stat.executeUpdate(Updatesentence);
Guys I am trying to make an update to an SQL database with this code and although I am not getting an error somewhere the code does not work with the desired result. The
System.out.println(Updatesentence);
is not printed and the update is not performed. I know there probably is somewhat of a syntax error on my String declaration, but I cannot work it out.
You have this:
String Updatesentence = "update bank set " + type + " = " + type + " + 1 where name = '" + name + "'";
So if the user's blood type is AB...
update bank set AB = AB + 1 where name = 'JohnSmith'
And that obviously won't work. You need to indicate the column in the database you want to be updating.
One of the most important things you need to remember when writing SQL statements, is to separate the query literal from the query arguments. This allows protection from SQL Injection and also makes it possible for the DB to reuse the query with different arguments (and "hard parsing" / optimizing the query only once). The way you do this with JDBC, is through prepared statements:
try (PreparedStatement queryPS = myConnection.prepareStatement(
"select * from donor where username = ?");
PreparedStatement updatePS = myConnection.prepareStatement(
"update bank set bloodtype = ? where name = ?");) {
queryPS.setString(1, username);
ResultSet rs = queryPS.executeQuery();
if (rs.next()) {
String type = rs.getString("bloodtype");
System.out.println("the user's blood type is: " + type);
updatePS.setString(1, type);
updatePS.setString(2, username);
updatePS.executeUpdate();
}
} catch (SQLException e) {
// handle it
}
When you use prepared statements, you don't need to worry about concatenating the inputs into the query; they will be sanitized and injected automatically. If you're doing things the "wrong way", it's really easy to make a mistake when you construct the query piece by piece from different variables in your code, and this is exactly what happened with the misplaced type variable in your example.
Your update statement is wrong. It should be :
String Updatesentence = "update bank set bloodtype = " + type + " + 1 where name = '" + name + "'" ;

Inserting values in specific row sql java

"SELECT * FROM PlayerClass WHERE Username = '" + p.getName() + "'"
So I have selected the specific row and how would I go about inserting a value in column ExColumn in the same exact row?
If you're allowed to use JDBC and PreparedStatement, I would suggest you do this:
String sql = "UPDATE PlayerClass SET ExColumn = ? WHERE Username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setObject(1, exColumnValue); // exColumnValue is the data you're trying to insert
ps.setString(2, p.getName());
ps.executeUpdate();
This way you'll be avoiding SQL injection attacks.
You have to use UPDATE
"Update PlayerClass set Username = '" +someValue + "'"
That will update all rows
To update secific rows with some condition ,add where clause.
"Update PlayerClass set Username = '" +someValue + "'
WHERE Username = '" + p.getName() + "'"
May be your are trying to update specific row. then this will help you
UPDATE PlayerClass SET ExColumn='YOUR_INSERTION_DATA_IN_THIS'
WHERE Username = 'XYZ'

Adding database column to JComboBox

I've searched around for the answer to this, but to no avail. When I compile this, it just returns the last row of my table in the database and not a list of the entire column as I expect. I believe the problem is from here.. If only I can make it list everything in that column, I'd be grateful for your help.
String query = "SELECT contact_id, first_name, last_name FROM my_contacts";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}//end while
When I compile this, it just returns the last row of my table in the
database and not a list of the entire column as I expect. I believe
the problem is from here..
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}
your code created a new instance of JComboBox, in each of loop inside while (rs.next()){
create JComboBox as local variable, then just to add Items in while-loop to instance that already exist and is intialized
best of ways is by using DeafultComboBoxModel for add / remove / modify an Items for JComboBox
Got everything up and running with this code.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/recall", "username", "password");
Statement statement = connection.createStatement();
String query = "SELECT * FROM names";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
String name = rs.getString("name");
names.addItem(rs.getString("name"));
}//end while
connection.close();
} catch (Exception e) {
e.printStackTrace();
}

why does execute() return true on an empty table?

Through the following snippet, I am trying to run a query that either updates the data or inserts a new data into the table named JustPinged. The table contains a column named NodesThatJustPinged and LastPingedAt. If there is already a node in NodesThatJustPinged then the time in milliseconds in LastPingedAt is updated. Otherwise a new node information is inserted.
The problem is, that the following snippet is unable to insert the data into the database's table. The reason is the statement:
boolean duplicateExists = searchToEliminateDuplicates.execute();
returns true to start with. (Initially the table is empty) Why does this statement return true? According to the documentation it returns true if the first result is a ResultSet object; false if the first result is an update count or there is no result. So here the boolean should contain a false value. But it contains a true value and thus the if statement always works. (And in if section,update query works when there is nothing to update !)
String searchQuery = "select NodesThatJustPinged from JustPinged where NodesThatJustPinged = '" + nodeInfo + "'";
PreparedStatement searchToEliminateDuplicates = connection.prepareStatement(searchQuery);
boolean duplicateExists = searchToEliminateDuplicates.execute();
if(duplicateExists) {
// update the LastPingedAt column in the JustPinged table
String updateQuery = "update JustPinged set LastPingedAt='" + pingedAt + "' where NodesThatJustPinged = '" + nodeInfo + "'";
PreparedStatement updateStatement = connection.prepareStatement(updateQuery);
updateStatement.executeUpdate();System.out.println("If statement");
} else {
// make a new entry into the database
String newInsertionQuery = "insert into JustPinged values('" + nodeInfo + "','" + pingedAt + "')";
PreparedStatement insertionStatement = connection.prepareStatement(newInsertionQuery);
insertionStatement.executeUpdate();System.out.println("else statement");
}
So how should I edit the code, so that duplicate values are updated and new values are inserted?
Your searchQuery will return ResultSet. hence the execute method returns 'true'. Try using executeQuery instead.
So your code would become:
String searchQuery = "select NodesThatJustPinged from JustPinged where NodesThatJustPinged = '" + nodeInfo + "'";
Statement searchToEliminateDuplicates = connection.createStatement();
ResultSet duplicateExists = searchToEliminateDuplicates.executeQuery(searchQuery);
if(duplicateExists.next()) {
// update the LastPingedAt column in the JustPinged table
String updateQuery = "update JustPinged set LastPingedAt='" + pingedAt + "' where NodesThatJustPinged = '" + nodeInfo + "'";
PreparedStatement updateStatement = connection.prepareStatement(updateQuery);
updateStatement.executeUpdate();System.out.println("If statement");
} else {
// make a new entry into the database
String newInsertionQuery = "insert into JustPinged values('" + nodeInfo + "','" + pingedAt + "')";
PreparedStatement insertionStatement = connection.prepareStatement(newInsertionQuery);
insertionStatement.executeUpdate();System.out.println("else statement");
}
P.S. If you are using PreparedStatement, then use parameters in your query and call ps.setString etc.
PPS. Don't use execute() method. Use executeQuery or executeUpdate. execute() is used where you don't know in advance whether your query is INSERT or UPDATE.
PPPS Close your resultset and statements as soon as you are done with them.
PPPPS A more better approach is to use count aggregate function in your SQL statement i.e.
select count(NodesThatJustPinged) from JustPinged where NodesThatJustPinged = '" + nodeInfo + "'";
Now you can check whether count is 0 or greater than 1 and branch your code accordingly.
A SELECT statement that returns zero rows will still return a ResultSet -- just one that immediately returns false when calling next(). You need to check the number of rows in the returned ResultSet.

Categories

Resources