I have a column of jsonb in Postgres.
Which contains data like "{\" name\":\"xyz\"}". I want to convert it as {"name":"xyz"}.
How can I achieve this?
Could you please clarify what exactly you want to do?
If you need to remove whitespaces in Java you can try something like this.
try (final Connection connection = embeddedPostgres.getTestDatabase().getConnection();
final Statement statement = connection.createStatement();
final PreparedStatement updateStatement = connection.prepareStatement("update your_table set your_column = ? where id = ?")) {
connection.setAutoCommit(false);
try (final ResultSet resultSet = statement.executeQuery("select * from your_table order by id limit 10")) {
while (resultSet.next()) {
final long id = resultSet.getLong("id");
final String infoAsString = resultSet.getString("info");
final String withoutWhitespaces = StringUtils.deleteWhitespace(infoAsString);
final PGobject fixedInfoObject = new PGobject();
fixedInfoObject.setType("jsonb");
fixedInfoObject.setValue(withoutWhitespaces);
updateStatement.setObject(1, fixedInfoObject);
updateStatement.setLong(2, id);
updateStatement.executeUpdate();
}
}
connection.commit();
}
Related
I want to insert input given by user into Sql Table using Java, but dont know how many coloumn is need.
eg.
insert into table_name values('"+id+"','"+name+"')
this query is not going to work because I don't know the column name i.e ID, name.
I want the query that is universal for any inserting data.
As per my need I tried this code. I HOPE IT WORKED FOR ALL.
void getTableInput(String tname, String dname) throws ClassNotFoundException, SQLException {
this.tname = tname;
this.dname = dname;
Scanner s = new Scanner(System.in);
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String conURL = "jdbc:sqlserver://localhost:1433;databaseName=" + this.dname + ";user=JT_DATA;password=1234";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM " + this.tname);
ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
String colName[] = new String[colNo];
String[] get_User_Input = new String[100];
for (int i = 1; i <=colNo; i++)
{
colName[i-1] = rsmd.getColumnLabel(i);
System.out.print(Arrays.toString(colName) + " : ");
get_User_Input[i-1] = s.next();
}
String store="";
for(int i=0;i<colNo;i++)
{
store += "'"+get_User_Input[i]+"',";
}
store = store.substring(0,store.length() -1);
PreparedStatement pst = con.prepareStatement("insert into "+this.tname+" values ("+ store +")");
pst.executeUpdate();
System.out.println("Data Inserted");
}
But the problem with this is that. This can only insert String Datatype.
I dont think there is any universal query.
If you dont know column name than you can find name of the column by using meta data.
You can get meta data of the connections (database)
DatabaseMetaData databaseMetaData = connection.getMetaData();
You can also get list of the tables.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = null;
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );
while(result.next()) {
String tableName = result.getString(3);
}
Listing column name in table.
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "my_table";
String columnNamePattern = null;
ResultSet result = databaseMetaData.getColumns(
catalog, schemaPattern, tableNamePattern, columnNamePattern);
while(result.next()){
String columnName = result.getString(4);
int columnType = result.getInt(5);
}
In this way you can find column name and can create query dynamically.
MysqlDatabase
This is my query to connect to my database.
SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam
FROM speler
WHERE Spel_Naam = ?
I work in the console of netbeans. When I want to show the records of table Speler with the Spel_Naam.
In the console I want to type a primary key of the table Spel and then it shows me the records of the table Speler in the console. How can I do this.
Like WHERE Spel_Naam = ?
The question mark need to be the name that I typed in
Is the select statement correct? I want to type the Spel_Naam in the console and then It must connect to the database and give me the records of table Speler. How can I do this?
public class SpelerMapper
{
private final static String LEES_SPELERS_SQL = "SELECT naam, kleur, sector, aantalZilverstukken, Spel_naam FROM speler WHERE Spel_Naam = ?";
public List<Speler> geefSpelers()
{
List<Speler> spelerLijst = new ArrayList<Speler>();
Statement statement;
Connection connection = PersistentieController.getInstance().getConnection();
try
{
statement = connection.createStatement();
// query database
ResultSet resultSet = statement.executeQuery(LEES_SPELERS_SQL);
while (resultSet.next())
{
String naam = resultSet.getString("naam");
String kleur = resultSet.getString("kleur");
int sector = resultSet.getInt("sector");
int aantalZilverstukken = resultSet.getInt("aantalZilverstukken");
Speler speler = new Speler(naam ,kleur, sector , aantalZilverstukken);
spelerLijst.add(speler);
}
statement.close();
return spelerLijst;
} catch (SQLException e)
{
e.printStackTrace();
}
return null;
}
Use PreparedStatements:
String LEES_SPELERS_SQL = "SELECT ... WHERE Spel_Naam = ?";
PreparedStatement prepStmt = con.prepareStatement(LEES_SPELERS_SQL);
prepStmt.setString(1, naam);
ResultSet rs = prepStmt.executeQuery();
Additional note: while being another option, concatenation of the SQL query is an unsafe way of doing the same task. Refer to this article for more info.
I have a bit of code here to get the next value of my sequence, but it is adding the total number of records onto the result each time.
I'm only learning about prepared Statements, I'm thinking this is something small, maybe rset.next() should be something else?
public void add( String title, String actor, String genre ) {
try {
String sql2 = "Select movie_seq.nextval from Movie";
pstmt = conn.prepareStatement(sql2);
rset = pstmt.executeQuery();
int nextVal = 0;
if(rset.next())
nextVal = rset.getInt(1);
String queryString = "Select MovieID, Title, Actor, Genre from Movie";
pstmt = conn
.prepareStatement(queryString,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rset = pstmt.executeQuery();
rset.moveToInsertRow();
rset.updateInt(1, nextVal);
rset.updateString(2, title);
rset.updateString(3, actor);
rset.updateString(4, genre);
rset.insertRow();
pstmt.executeUpdate();
} catch (SQLException e2) {
System.out.println("Error going to previous row");
System.exit(1);
}
}
Any help appreciated.
I think you don't need the call to pstmt.executeUpdate();
As stated in ResultSet doc, the function insertRow stores the row in the Dataset AND in the database.
The following code shows all that's necessary to add a new row:
rset.moveToInsertRow(); // moves cursor to the insert row
rset.updateString(1, "AINSWORTH"); // updates the
// first column of the insert row to be AINSWORTH
rset.updateInt(2,35); // updates the second column to be 35
rset.updateBoolean(3, true); // updates the third column to true
rset.insertRow();
rset.moveToCurrentRow();
Why dont you iterate using while rather than if . something like this
List lst = new ArrayList();
Someclass sc = new SomeClass(); //object of the class
String query = "SELECT * from SomeTable";
PreparedStatement pstmt = sqlConn.prepareStatement(query);
ResultSet rs = pstmt.executeQuery();
Role role = null;
while (rs.next()) {
String one = rs.getString(1);
String two = rs.getString(2);
boolean three = rs.getBoolean(3);
//if you have setters getters for them
sc.setOne(one);
sc.setTwo(two);
sc,setThree(three);
lst.add(sc)
}
//in the end return lst which is of type List<SomeClass>
}
Shouldn't you be doing this instead?:
String sql2 = "Select " + movie_seq.nextval + " from Movie";
As it is, it seems like you're passing a slightly bogus string into the SQL query, which is probably defaulting to the max index (not 100% positive on that). Then rs.next() is just incrementing that.
I am trying to display data from the database into a datatable and I am getting no results. I tested the queries with JDBC with exact select statement to see if it returns any row, and it always worked. But when I try to have the data from the database into my datatable I get no results. I even made a fake dummy data just to populate my datatable. I must be doing something wrong in the index.xhtml file that I don't know of. What could I doing wrong ? any help would be appreciated ?
edit: first I went to with Primefaces with their datatable example, and than I went with simple jsf style datatable like I have here and neither of those worked when I try to do it with the database
UserDAO.java
public class UserDAO {
private static final String USERNAME = "something";
private static final String PASSWORD = "something";
private static final String CONN_STRING =
"jdbc:sqlserver://petunia.arvixe.com.....something";
public List<Report> getUserList() {
List<Report> list = new ArrayList<Report>();
PreparedStatement ps = null;
Connection con = null;
ResultSet result = null;
try {
con = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
while (result.next()) {
Report rep = new Report();
rep.setId(result.getInt("id"));
rep.setTag(result.getString("tag"));
rep.setName(result.getString("asset_name"));
rep.setModel(result.getString("model"));
rep.setSerial(result.getString("ser_no"));
rep.setValue(result.getFloat("value"));
rep.setCondition(result.getString("asset_condition"));
rep.setType(result.getString("asset_type"));
rep.setLocationName(result.getString("name"));
rep.setAddress(result.getString("address"));
rep.setCity(result.getString("city"));
rep.setState(result.getString("state"));
rep.setZip(result.getString("zip"));
rep.setPhone(result.getString("phone"));
rep.setDistrict(result.getInt("district"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
}
Well, you are making a report:
Report rep = new Report();
...but not adding it to your list. Add this:
Report rep = new Report();
list.add(rep);
I suppose your problem is this code:
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You are overwriting your sql statement immediately with the statement sql1.
I think, you probably want to select the assets with THEIR locations. In SQL you can use a JOIN to achieve that.
If you use this syntax
String sql = "SELECT id, tag,asset_name, model, ser_no, value, \n" +
" asset_condition, asset_type FROM assets";
String sql1 = "SELECT name, address, city,state,zip, phone, district FROM location";
ps = con.prepareStatement(sql);
ps = con.prepareStatement(sql1);
result = ps.executeQuery();
You will get as a result only the execution of the second query. I think that in your case you are trying to get a result from both tables assets and location so you should use a join between the 2 tables.
I want to create Java method which can count the rows in Oracle table. So far I made this:
public int CheckDataDB(String DBtablename, String DBArgument) throws SQLException {
System.out.println("SessionHandle CheckUserDB:"+DBArgument);
int count;
String SQLStatement = null;
if (ds == null) {
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException();
}
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQLStatement = "SELECT count(*) FROM ? WHERE USERSTATUS = ?";
ps = conn.prepareStatement(SQLStatement);
ps.setString(1, DBtablename);
ps.setString(2, DBArgument);
ResultSet result = ps.executeQuery();
if (result.next()) {
count = result.getString("Passwd");
}
conn.commit();
committed = true;
} finally {
if (!committed) {
conn.rollback();
}
}
} finally {
/* Release the resources */
ps.close();
conn.close();
}
return count;
}
I want to use for different tables. This is the problem that I cannot solve:
count = result.getString("row");
Can you help me to solve the problem?
count = result.getInt(1);
This is needed, because count is int. And you can specify the index of the row returned by the query, you don't need to access it by name.
But you could also do:
count = result.getInt("count(*)");
This should do it:
count = result.getInt("count(*)");
You need to use the same name as you specified in your query to get the value. You could also make your
count = result.getString("row");
work by changing your query to
SQLStatement = "SELECT count(*) as row FROM ? WHERE USERSTATUS = ?";
You cannot use bind variable in place of a database object in an SQL query, can you? It can only be used for parameter binding.
Try this instead,
"SELECT count(*) as row_count FROM " + DBtablename + " WHERE USERSTATUS = ?";
This could be vulnerable to SQL Injection so you might want to check that DBtablename parameter is a valid database object name (i.e. at most 30 bytes long without spaces, and contains only valid chars for database object identifiers).
count = result.getInt("row_count");