Here i made table called sub_master with column sub_id and name, insertion and deletion working perfectly fine with this, so put those functions here as well to get reference for update function
and i'm using PostgreSQL for this.
In command line UPDATE query is working fine and query as:
UPDATE school_submaster SET name ='' WHERE sub_id = ;
private void InsertRowActionPerformed(java.awt.event.ActionEvent evt)
{
String query = "INSERT INTO school_submaster (sub_id, \"name\") VALUES ("+SidInput.getText()+",'"+SnameInput.getText()+"')";
executeSQlQuery(query, "Inserted");
}
private void UpdateRowActionPerformed(java.awt.event.ActionEvent evt)
{
String query = "UPDATE school_submaster SET 'name' ='"+SnameInput.getText()+"'+WHERE sub_id = "+SidInput.getText();
executeSQlQuery(query, "Updated");
}
private void DeleteRowActionPerformed(java.awt.event.ActionEvent evt)
{
String query = "DELETE FROM school_submaster WHERE sub_id = "+SidInput.getText();
executeSQlQuery(query, "Deleted");
}
Only use single quotes for string and date constants. Never use single quotes around column names or table names.
Your update is:
UPDATE school_submaster
SET 'name' ='<something>'+WHERE sub_id = "+SidInput.getText();
This has the additional issue of a + in the query string. It should look ore like:
UPDATE school_submaster
SET name = '<something>'
WHERE sub_id = "+SidInput.getText();
But even that is not true. You need to learn to use parameters to pass parameters into queries. The query should be some variant of:
UPDATE school_submaster
SET name = ?
WHERE sub_id = ?
Where the ? is a placeholder for a parameter (it might also be #name or something else).
You are missing a space in the sql WHERE clause, so add it as shown below:
String query = "UPDATE school_submaster SET 'name' ='"+
SnameInput.getText()+"' WHERE sub_id = "+SidInput.getText();
Related
I am created a prepared select query and it appears the query is not picking up the DESC or I have the bind_param structured wrong. I am trying to get the last id of the user_id's image to display. The user's image displays, but it is the first id image they have. I tried doing ASC and it was the same thing.
Am I doing this right?
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY ? DESC LIMIT 1
";
if ($stmt = $con->prepare($sql)) {
$stmt->bind_param("ss", $user_id, `id`);
$stmt->execute();
if (!$stmt->errno) {
// Handle error here
}
$stmt->bind_result($id, $user_id, $profilePic);
$pics = array();
while ($stmt->fetch()) {
$pics[] = $profilePic;
}
echo '<img id="home-profile-pic" src=" '.$profilePic.'">';
}
I don't think you can :
Use placeholders in an order by clause
Bind column names : you can only bind values -- or variables, and
have their value injected in the prepared statement.
You can use number instead of field name in the 'order by' clause
Why you have put ? after "order by" statement?
Your order by should reference to either id of your "profile_img" table or any timestamp field in that table...
e.g. $sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY id DESC LIMIT 1
";
here replace id (i am assuming this name) with the primary key field name of profile_image table
or
$sql = "
SELECT *
FROM profile_img
WHERE user_id = ?
ORDER BY created_on DESC LIMIT 1
";
here created_on (which i have also assumed) can be replaced by any timestamp field if you any in profile_img table
I am planning to execute an update statement using a prepared statement that makes use of a dynamically changing number of columns. for eg: in the first update statement I update only name and age of a table. in the second instance, I update age, city, state, country..etc. in the next instance, I update 150 columns like this.
can someone provide me what is the perfect approach for this in java?
following is the example
If the user provides input for name and age then I update
UPDATE table1 set name = <> ,age = <>;
If the user provides input for city name state country and pin then the update statement should be like this-
UPDATE table1 set name = <>, city = <>,state= <>,country=<>, pin = <>;
Build your sql query like this
update demotable set col1 = case when #col1 is null then col1 else #col1 end
OR
Here #col is passed as value from front end.
from which you may create dynamic sql
declare #col1 nvarchar(max) /// from front you can pass your column value with its column name like: col1 = 'col1'
declare #Query = 'update demotable set = ' + #col1 /// it create query as update demotable set col1 = 'col1'
PREPARE stmt1 FROM #Query ;
EXECUTE stmt1
DEALLOCATE PREPARE stmt1;
I am new to MYSQL but this logic will surely work.
You can write one statement like this:
UPDATE table1
SET name = COALESCE(?, name),
age = COALESCE(?, age),
city = COALESCE(?, city),
. . .
Notes:
This assumes that the values are not being set to NULL.
The ? is a placeholder for a parameter. Don't munge query strings with user input.
Presumably you want a WHERE clause to limit what rows get updated.
Im trying to create an SQL Statement that will differentiate between employees types. For example if the Boolean Type Manager Column is checked it will return. Im using the info to fill a Manager on Duty JCombo in Java.
Im trying
String sql = "SELECT Employees.Name FROM Employees WHERE Manager = 'true' ORDER BY Name ASC";
Cant seem to get it right.
In SQL the boolean field will be a bit so your SQL statement will need to be
String sql = "SELECT Employees.Name FROM Employees WHERE Manager = 1 ORDER BY Name ASC";
in SQL a boolean field is a bit field (0 or 1) so you have to check as:
String sql = "SELECT Employees.Name FROM Employees WHERE Manager = 1 ORDER BY Name ASC"
In PostgreSQL user is a reserved keyword that is used in an internal table, however I also have a separate user table in my own database that I need to use. Whenever I try to execute INSERT or UPDATE statements on the table, it generates the following error: The column name 'id' was not found in this ResultSet.
This is the Java code I am currently using:
PreparedStatement stat1 = conn.prepareStatement("SELECT id FROM user;");
PreparedStatement stat2 = conn.prepareStatement("UPDATE user SET date_created = ? , last_updated = ? , uuid = ? WHERE id = ?;");
ResultSet rs = stat1.executeQuery();
while(rs.next()){
UUID uuid = UUID.randomUUID();
String tempId = uuid.toString();
stat2.setTimestamp(1, curDate);
stat2.setTimestamp(2, curDate);
stat2.setString(3, tempId);
stat2.setLong(4,rs.getLong("id"));
stat2.executeUpdate();
}
So my question is, how could I insert or update the values in my personal user table without interfering with the keyword restriction?
Use this:
prepareStatement("UPDATE \"user\" set date_created = ?")
Or, better yet, rename your user table to something else, like users:
ALTER TABLE "user" RENAME TO users;
Escape the table name like this
select * from "user";
I am having some problems and I'm sure it's something stupid.
So I have a query like
SELECT name, id, xyz FROM table ORDER BY ?
then later down the road setting the ? doing a
ps.setString(1, "xyz");
I am outputting the query and the value of xyz in the console. When I loop through the ResultSet returned from the PreparedStatement the values are not in the correct order. They are in the returned order as if I had left the ORDER BY clause off. When I copy/paste the query and the value into TOAD it runs and comes back correctly.
Any ideas to why the ResultSet is not coming back in the correct order?
The database will see the query as
SELECT name, id, xyz FROM table ORDER BY 'xyz'
That is to say, order by a constant expression (the string 'xyz' in this case). Any order will satisfy that.
? is for parameters, you can't use it to insert column names. The generated statements will look something like
SELECT name, id, xyz FROM table ORDER BY 'xyz'
so that your entries are sorted by the string 'xyz', not by the content of column xyz.
Why not run:
ps.setInteger(1, 3);
Regards.
EDIT: AFAIK Oracle 10g supports it.
PreparedStatement placeholders are not intend for tablenames nor columnnames. They are only intented for actual column values.
You can however use String#format() for this, that's also the way I often do. For example:
private static final String SQL_SELECT_ORDER = "SELECT name, id, xyz FROM table ORDER BY %s";
...
public List<Data> list(boolean ascending) {
String order = ascending ? "ASC" : "DESC";
String sql = String.format(SQL_SELECT_ORDER, order);
...
Another example:
private static final String SQL_SELECT_IN = "SELECT name, id, xyz FROM table WHERE id IN (%s)";
...
public List<Data> list(Set<Long> ids) {
String placeHolders = generatePlaceHolders(ids.size()); // Should return "?,?,?..."
String sql = String.format(SQL_SELECT_IN, placeHolders);
...
DAOUtil.setValues(preparedStatement, ids.toArray());
...
The database will see the query like this
SELECT name, id, xyz FROM table ORDER BY 'xyz'
I think you should add more variable like order_field and order_direction
I assume you have a method like below and I give you an example to solve it
pulbic List<Object> getAllTableWithOrder(String order_field, String order_direction) {
String sql = "select * from table order by ? ?";
//add connection here
PreparedStatement ps = (PreparedStatement) conn.prepareStatement(sql);
ps.setString(1,order_field);
ps.setString(2,order_direction);
logger.info(String.valueOf(ps)); //returns something like: com.mysql.jdbc.JDBC4PreparedStatement#a0ff86: select * from table order by 'id' 'desc'
String sqlb = String.valueOf(ps);
String sqlc = sqlb.replace("'"+order_field+"'", order_field);
String sqld = sqlc.replace("'"+order_direction+"'", order_direction);
String[] normQuery = sqld.split(":");
ResultSet result = conn.createStatement().executeQuery(normQuery[1]);
while(result.next()) {
//iteration
}
}