Inserting values in specific row sql java - 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'

Related

Can't Update the SQL through Java

I'm trying to make CRUD (Create, Read, Update, Delete) to my projects. But it seems the "update" doesn't work. It keeps saying
java.sql.SQLSyntaxErrorException : You have an error in your SQL syntax; check the manual that coresponds to your MariaDB server version for the right syntax to use near "Number" = 0813874810 WHERE Name = "Gregory" at line 1)
What the solution for this?
Here is my code:
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata", "root", "");
String sql = "UPDATE employeetab SET Name = '" + txtEmployeeName.getText()
+ "',Address = '" + txtEmployeeAddress.getText()
+ "',Gender = '" + gender_type
+ "',Phone Number = '" + txtEmployeePhone.getText()
+ "' WHERE Name = '" + txtEmployeeName.getText() + "'";
stm = conn.prepareStatement(sql);
stm.execute(sql);
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
Problem comes from the space in column Phone Number. To make it work you need to escape the column name with `.
UPDATE employeetab
SET Name = 'something',Address = 'some address',Gender = 'whatever',`Phone Number` = '000000000'
WHERE Name = 'something';
You should follow sql naming conventions, normally words in column names are separated by _. Your column name should be - phone_number.
Also, as mentioned in comments, you should not just add user input into sql queries, because you are leaving yourself wide open for sql injection.
You need to follow the naming conventions , their is space between 'Phone Number' column you should not write like this you need to add _ in between of this two.
try this :
String gender_type = null;
if (ButtonM.isSelected()){
gender_type = "Male";
}else if(ButtonFM.isSelected()){
gender_type = "Female";
}
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employeedata","root","");
String sql = "UPDATE employeetab SET Name = ? ," +
" Address = ? ," +
" Gender = ? ," +
" Phone Number = ? ," +
" WHERE Name = ? ," ;
PreparedStatement pStmt = conn.prepareCall(sql);
pStmt.setString(1, txtEmployeeName.getText()+"");
pStmt.setString(2, txtEmployeeAddress.getText()+"");
pStmt.setString(3, gender_type+"");
pStmt.setString(4, txtEmployeePhone.getText()+"");
pStmt.setString(5, txtEmployeeName.getText());
pStmt.executeUpdate();
JOptionPane.showMessageDialog(this, "Update successfully");
this.setVisible(false);
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
its cleaner and should work.

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 ?

JDBC Delete Query with multiple conditions

I have been struggling with an SQL Delete query. I want it to delete a row, Where 2 conditions are met. The error I am getting says my SQL Syntax is wrong near the end at the last ')'.
String sql = "DELETE FROM course
WHERE (username_entry = " + username +
" AND course_name = " + courseToDelete.toUpperCase() + ")";
My variables have the right values and the data in the database corresponds perfectly.
Here is an example of what your raw query might look like:
DELETE
FROM course
WHERE username_entry = tim AND course_name = chemistry;
Of course, this is not valid SQL, because you are comparing text columns against what will be perceived as other columns called tim and chemistry. You really want the above query to look like this:
DELETE
FROM course
WHERE username_entry = 'tim' AND course_name = 'chemistry';
In other words, you need to compare against properly escaped string literals. But in practice, the best thing to do is to use prepared statements, which handle the formatting automatically:
String sql = "DELETE FROM course WHERE username_entry = ? AND course_name = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, courseToDelete.toUpperCase());
ps.executeUpdate();
You need to encapsulate string values into quotes
String sql = "DELETE FROM course
WHERE (username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase() + "')";
But better way is to use prepared statements as they do automatical escape
Did you try to remove the braces after the Where clause.
The query would look like below after the change:
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete.toUpperCase()+"'";
You don't have to use any open / close paranthesis for the query as such!
As suggested in the other answers, you don't really need to use the injection of variables but instead, use the PreparedStatement
String sql = "DELETE FROM course
WHERE username_entry = '" + username +
"' AND course_name = '" + courseToDelete +"'";
Hope this helps!

Populating jTable from postgresql

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

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