I have a JSONB column in my postgres table, I want to update the some fields in that column using JDBC.
Please help to for a JDBC query to update JSONB column.
I guess you would need to first connect by creating the object 'conn' in your code base with something of the like, more details on this step here.
// create a Statement from the connection
Statement statement = conn.createStatement();
and then embed the SQL query in the JDBC as usual in Java yes.
And write the appropiate query, this should work for example in order to leave null all entries with marketplace equal to US:
// update the data
statement.executeUpdate("UPDATE mytable SET App = jsonb_set(App, '{marketplace}', '""') where data ->>'marketplace' = 'US' ");
Related
I have a function that insert a single record into a PostgreSQL database.
My question is how do i get the ID of the inserted record since the ID is auto generated
This is the code
postgreSQLClient.getConnection(ar -> {
if(ar.failed())
LOGGER.error("saving message error:", ar.cause());
else{
SQLConnection conn = ar.result();
conn.queryWithParams(insertStr.toString(), sqlParam, rs -> {
conn.close();
Constant.LOGGER.info("Save ID: " +rs.result());
});
}
});
Add a RETURNING clause to your insert statement. See https://www.postgresql.org/docs/current/static/sql-insert.html
This is from the vert.x documentation, see https://vertx.io/docs/vertx-mysql-postgresql-client/java/
Note about last inserted ids
When inserting new rows into a table, you might want to retrieve auto-incremented ids from the database. The JDBC API usually lets you retrieve the last inserted id from a connection. If you use MySQL, it will work the way it does like the JDBC API. In PostgreSQL you can add the "RETURNING" clause to get the latest inserted ids. Use one of the query methods to get access to the returned columns.
I have a mariadb table with 2 cols: rowid int pk autogenerated and imagen blob.
By using "CallableStatement sentence = mariaConn.prepareCall(myinsert);" I'm able to add a new row with a blob into "imagen" BUT I can't get the autogenerated pk col "rowid".
By the other hand, using "Statement sentence = mariaConn.prepareStatement(myinsert);" I can get the autogenerated col "rowid" but I can't add a blob into "imagen" (only do if it is empty).
Is there a way to do both things at one call? (trying to avoid a Statement insert to get the pk and then a CallableStatement to update the blob).
Note: in Oracle is pretty simple using CallableStatement because Oracle's insert has a "returning" clause <= I'm trying to emulate it on mariadb.
Thanks in advance.
you do not need CallableStatement to insert blob, a simple prepared statement
insert into table(imagen) values(?)
works,and with that you can get autogenerated value if you use Statement.RETURN_GENERATED_KEYS during preparation, and Statement.getGeneratedKeys() after execution. You also can do
select last_insert_id()
any time, but this is less efficient.
There is no MariaDB 5.6 btw.
I want to update two sql tables at once in java. I'm using SQLiteManager. Could someone please suggest a way of doing that?
Assuming you have the driver and connection to the database, you should be able to run most sql commands from java. There is not a single sql statement that will update two tables at once but you can update each table in turn which will have the same effect.
See http://www.javaworkspace.com/connectdatabase/connectSQLite.do for some examples.
For a table update, use
statement.execute(sql);
where sql is a string of the form
sql = "UPDATE myTable SET myColumn = newValue WHERE someOtherColumn=value";
If I have a SQL table with columns:
NR_A, NR_B, NR_C, NR_D, R_A, R_B, R_C
and on runtime, I add columns following the column's sequence such that the next column above would be R_D followed by R_E.
My problem is I need to reset the values of columns that starts with R_ (labeled that way to indicate that it is resettable) back to 0 each time I re-run my script . NR_ columns btw are fixed, so it is simpler to just say something like:
UPDATE table set col = 0 where column name starts with 'NR_'
I know that is not a valid SQL but I think its the best way to state my problem.
Any thoughts?
EDIT: btw, I use postgres (if that would help) and java.
SQL doesn't support dynamically named columns or tables--your options are:
statically define column references
use dynamic SQL to generate & execute the query/queries
Java PreparedStatements do not insulate you from this--they have the same issue, just in Java.
Are you sure you have to add columns during normal operations? Dynamic datamodels are most of the time a realy bad idea. You will see locking and performance problems.
If you need a dynamic datamodel, take a look at key-value storage. PostgreSQL also has the extension hstore, check the contrib.
If you don't have many columns and you don't expect the schema to change, just list them explicitly.
UPDATE table SET NR_A=0;
UPDATE table SET NR_B=0;
UPDATE table SET NR_C=0;
UPDATE table SET NR_D=0;
Otherwise, a simple php script could dynamically build and execute your query:
<?php
$db = pg_connect("host=localhost port=5432 user=postgres password=mypass dbname=mydb");
if(!$db) die("Failed to connect");
$reset_cols = ["A","B","C","D"];
foreach ($col in $reset_cols) {
$sql = "UPDATE my_table SET NR_" . $col . "=0";
pg_query($db,$sql);
}
?>
You could also lookup table's columns in Postgresql by querying the information schema columns tables, but you'll likely need to write a plpgsql function to loop over the query results (one row per table column starting with "NR_").
if you rather using sql query script, you should try to get the all column based on given tablename.
maybe you could try this query to get all column based on given tablename to use in your query.
SELECT attname FROM
pg_attribute, pg_type
WHERE typname = 'tablename' --your table name
AND attrelid = typrelid
AND attname NOT IN ('cmin', 'cmax', 'ctid', 'oid', 'tableoid', 'xmin', 'xmax')
--note that this attname is sys column
the query would return all column with given tablename except system column
String link = "http://hosted.ap.org";
I want to find whether the given url is already existing in the SQL DB under the table name "urls". If the given url is not found in that table i need to insert it in to that table.
As I am a beginner in Java, I cannot really reach the exact code.
Please advise on this regard on how to search the url in the table.
I am done with the SQL Connection using the java code. Please advise me on the searching and inserting part alone as explained above.
PreparedStatement insert = connectin.preparedStateme("insert into urls(url) vlaues(?)");
PreparedStatement search = connectin.preparedStateme("select * from urls where url = ?");
search.setString(1, <your url value to search>);
ResultSet rs = search.executeQuery();
if (!rs.hasNext()) {
insert.setString(1, <your url value to insert>);
insert.executeUpdate();
}
//finally close your statements and connection
...
i assumed that you only have one field your table and field name is url. if you have more fields you need to add them in insert query.
You need to distinguish between two completely separate things: SQL (Structured Query Language) is the language which you use to communicate with the DB. JDBC (Java DataBase Connectivity) is a Java API which enables you to execute SQL language using Java code.
To get data from DB, you usually use the SQL SELECT statement. To insert data in a DB, you usually use the SQL INSERT INTO statement
To prepare a SQL statement in Java, you usually use Connection#prepareStatement(). To execute a SQL SELECT statement in Java, you should use PreparedStatement#executeQuery(). It returns a ResultSet with the query results. To execute a SQL INSERT statement in Java, you should use PreparedStatement#executeUpdate().
See also:
SQL tutorial
JDBC tutorial