I am developing an application that can update my database... However, I can't get my Java method working correctly. It gives me the following error: Must declare the scalar variable "#P0WHERE". Any suggestions?
The method I am using:
public void updateTable() throws SQLException
{
Scanner input = new Scanner(System.in);
System.out.println("Update the following:\n" + this);
this.getReservationInfo(input);
DataConnection connection = new DataConnection();
String query = "UPDATE " + TableName;
query += "Set Name = ?";
query += "WHERE Person_ID = " + id;
connection.updateData(query, person_name);
connection.closeConnection();
}
Add spaces before 'SET' and 'WHERE', otherwise it will not work.
String query = "UPDATE " + TableName;
query += " SET Name = ?";
query += " , Age = ?";
query += " , Col1 = ?"; //And other cols
query += " WHERE Person_ID = " + id;
EDIT: Changed query to update multiple columns.
I think so. You seem to be missing spaces. After the TableName and after the ?.
String query = "UPDATE " + TableName;
query += " Set Name = ?"; // tableSet not good, and
// ?WHERE is not valid add spaces.
query += " WHERE Person_ID = " + id;
Related
I am struggling with checking if a table exist in the DB. What I have done so far is as follows:
public boolean isTableExist(String tableName) {
JdbcTemplate jdbc = getJdbcTemplate();
String query =
"IF (OBJECT_ID(?) IS NOT NULL ) "
+ "BEGIN "
+ " PRINT 1 "
+ " RETURN "
+ "END "
+ "ELSE "
+ "BEGIN "
+ " PRINT 0 "
+ " RETURN "
+ "END";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
return result == 1 ? true : false;
}
Output (Error):
PreparedStatementCallback; uncategorized SQLException for SQL [IF
(OBJECT_ID(?) IS NOT NULL ) BEGIN PRINT 1 RETURN END ELSE BEGIN
PRINT 0 RETURN END]; SQL state [null]; error code [0]; The statement
did not return a result set.; nested exception is
com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not
return a result set.
You can also run a query like so:
select count(*)
from information_schema.tables
where table_name = 'yourtablename'
-- optionally this too
-- and table_schema = 'dbo';
If you get zero, table doesn't exist.
Based on jdbctemplate count queryForInt and pass multiple parameters answer, it seems like you might have to use something like this once you store the query
jdbc.queryForObject(
"select count(*) from information_schema.tables where table_name = ?"
, new Object[] { tableName }
, Integer.class
);
Update:
The problem has been resolved with the help of this post and the final solution based on the above info is:
String query =
"select count(*) "
+ "from information_schema.tables "
+ "where table_name = ? and table_schema = 'dbo'";
Integer result = jdbc.queryForObject(query, Integer.class, tableName);
I am creating the Spring Boot application with a PostgreSQL database. and I am using JDBCTemplate to perform DB operations. as per my requirement, I want a count of the row from CONTRACT_VIEW_2 table where the value of LICENSE_PLATE = "xxxxxx" and ZONE_CODE is IN ("x","y","z") but I am getting PSQL Exception.
I tried using MapSQLParameterSource but still, I facing the issue.
#Override
public Integer getAllZoneForLp(String lp,List<String> zones) {
MapSqlParameterSource zoneIds = new MapSqlParameterSource();
zoneIds.addValue("zoneIds",zones);
String sql = "select " +
"count(*) " +
"from contract_view_2 " +
"where license_plate = ? and zone_code IN (?)";
return jdbcTemplate.queryForObject(sql,Integer.class,lp,zoneIds);
}
I expect the row count in the result but I am getting PSQL Exception. I am attaching the image of the exception which I am getting.
Thanks in advance.
The problem with yours is you have added Namedparameter to JdbcTemplate.
So in case you are using NamedParameterJdbcTemplate
#Override
public Integer getAllZoneForLp(String lp,List<String> zones) {
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("lp", lp);
parameters.addValue("zoneIds",zones);
String sql = "select " +
"count(*) " +
"from contract_view_2 " +
"where license_plate = :lp and zone_code IN (:zoneIds)";
NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
return namedParameterJdbcTemplate.queryForObject(sql, parameters, Integer.class);
}
In case you want to use jdbcTemplate
#Override
public Integer getAllZoneForLp(String lp,List<String> zones) {
String sql = "select " +
"count(*) " +
"from contract_view_2 " +
"where license_plate = ? and zone_code IN (?)";
return jdbcTemplate.queryForObject(sql, Integer.class, new Object[] { lp, zones});
}
Go with NameParameterJdbcTemplate so that you won't miss any params.
Please change your query to
String sql = "select " +
"count(*) " +
"from contract_view_2 " +
"where license_plate = ? and zone_code IN (:zoneIds)";
Changes: changed ? to :zoneIds
Line zoneIds.addValue("zoneIds",zones); is using named parameter to bind it.
I am trying to query a MS Access database from my java code and I am having no luck with the % wildcard that I read should work in other posts. The LIKE operator works if I exclude the wild cards from my code and provide the searchText variable with a value that matches exactly to a records Description. Below is the String queries I have tried that have either returned null or an exception:
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '%" searchText + "%' ORDER BY [WorkOrderNo] DESC", tableName);
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE '*" searchText + "*' ORDER BY [WorkOrderNo] DESC", tableName);
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \"%" searchText + "%\" ORDER BY [WorkOrderNo] DESC", tableName);
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
String tableName = "SSPWO";
String desc = "[Description]";
String query = String.format("SELECT * FROM %s WHERE " + desc + " LIKE \'%" searchText + "%\' ORDER BY [WorkOrderNo] DESC", tableName);
Any help is greatly appreciated.
The percent sign (%) is definitely the right wildcard character to use in this case. For test data
ID Description
-- -----------------------------------
1 I like apple pie.
2 This is a test.
3 Apple makes iThings.
4 This is another test.
5 Name of a tropical fruit: pineapple
the code
String tableName = "SSPWO";
String desc = "[Description]";
String searchText = "apple";
PreparedStatement ps = con.prepareStatement(
String.format("SELECT * FROM %s WHERE %s LIKE ?", tableName, desc)
);
ps.setString(1, "%" + searchText + "%");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(String.format("%d: %s", rs.getInt(1),rs.getString(2)));
}
produces the following console output
1: I like apple pie.
3: Apple makes iThings.
5: Name of a tropical fruit: pineapple
You've got a whack of syntax errors anyways:
String query = String.format([..snip...] + " LIKE '%" searchText
^---missing +
I want to copy values from songDetails table to playlistDetails table.
here is my code :
public void transferData(String name) {
SQLiteDatabase db = this.getWritableDatabase();
String selectQuery = "INSERT INTO "+ TABLE_CURRENTLIST + " SELECT * FROM " + TABLE_DATA + " WHERE " + KEY_ALBUMNAME+ " = " + name + "";
db.execSQL(selectQuery);
}
While executing this code, it throws this exception
01-31 01:29:49.426: E/AndroidRuntime(3102): android.database.sqlite.SQLiteException: no such column: unknown (code 1): , while compiling: INSERT INTO PlayListDetails SELECT * FROM songDetails WHERE albumName = unknown
the value of 'name' variable is correct. And i want to copy only the rows which have the albumName as unknown.
I'm struggled with this. Please help me.
You are missing single quotes around query param value (unknown).
Your query should be
String selectQuery = "INSERT INTO "+ TABLE_CURRENTLIST + " SELECT * FROM " + TABLE_DATA + " WHERE " + KEY_ALBUMNAME+ " = '" + name + "'";
My suggestion would be to use PreparedStatement style parameters.
This code using JPA2 criteria query return an empty result list:
CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
CriteriaQuery<VwReplPrevia> query = criteriaBuilder.createQuery(VwReplPrevia.class);
Root<VwReplPrevia> root = query.from(VwReplPrevia.class);
query.multiselect(root.get(VwReplPrevia_.codigoCentroCustos),
root.get(VwReplPrevia_.numeroCartaoPostagem),
root.get(VwReplPrevia_.codigoServico),
root.get(VwReplPrevia_.quantidadeItems),
root.get(VwReplPrevia_.valorServico));
TypedQuery<VwReplPrevia> typedQuery = getEntityManager().createQuery(query);
String contrato = StringUtils.trim(paginador.getEntityBean().getContrato());
String centroCustos = StringUtils.trim(paginador.getEntityBean().getCentroCustos());
String cartaoPostagem = StringUtils.trim(paginador.getEntityBean().getCartaoPostagem());
String servico = StringUtils.trim(paginador.getEntityBean().getServico());
query.where(criteriaBuilder.equal(root.get(VwReplPrevia_.numeroContrato), contrato));
if (StringUtils.isNotBlank(centroCustos)) {
criteriaBuilder.and(criteriaBuilder.equal(root.get(VwReplPrevia_.codigoCentroCustos), "9912231583"));
}
if (StringUtils.isNotBlank(cartaoPostagem)) {
criteriaBuilder.and(criteriaBuilder.equal(root.get(VwReplPrevia_.numeroCartaoPostagem), cartaoPostagem));
}
if (StringUtils.isNotBlank(servico)) {
criteriaBuilder.and(criteriaBuilder.equal(root.get(VwReplPrevia_.codigoServico), servico));
}
query.orderBy(criteriaBuilder.asc(root.get(VwReplPrevia_.codigoCentroCustos)));
query.groupBy(root.get(VwReplPrevia_.codigoCentroCustos),
root.get(VwReplPrevia_.numeroCartaoPostagem),
root.get(VwReplPrevia_.codigoServico),
root.get(VwReplPrevia_.quantidadeItems),
root.get(VwReplPrevia_.valorServico));
List<VwReplPrevia> resultado = typedQuery.getResultList();
The same query, using native query, return the corret number of results.
String sql = "SELECT vwreplprev0_.sdan8 AS col_0_0_, " +
"vwreplprev0_.sdcnid AS col_1_0_, " +
"vwreplprev0_.sdlitm AS col_2_0_, " +
"vwreplprev0_.sduorg AS col_3_0_, " +
"vwreplprev0_.sdaexp AS col_4_0_ " +
"FROM sfe_view.vw_f4211_repl_previa vwreplprev0_ " +
"WHERE vwreplprev0_.sddmct = '9912231583' " +
"GROUP BY vwreplprev0_.sdan8, " +
"vwreplprev0_.sdcnid, " +
"vwreplprev0_.sdlitm, " +
"vwreplprev0_.sduorg, " +
"vwreplprev0_.sdaexp " +
"ORDER BY vwreplprev0_.sdan8 ASC ";
Collection<PreviaFaturaBean> result = getEntityManager().createNativeQuery(sql).getResultList();
paginador.setColecaoDeRegistros(result);
I have no idea what's the problem. My only reference in implementing via Criteria Query was http://docs.oracle.com/javaee/6/tutorial/doc/gjivm.html, someone can give me a hint?
The following part looks wrong, and not matching with the native query:
query.where(criteriaBuilder.equal(root.get(VwReplPrevia_.numeroContrato), contrato));
if (StringUtils.isNotBlank(centroCustos)) {
criteriaBuilder.and(criteriaBuilder.equal(root.get(VwReplPrevia_.codigoCentroCustos), "9912231583"));
}
It should probably be
query.where(criteriaBuilder.equal(root.get(VwReplPrevia_.numeroContrato), "9912231583"));
if (StringUtils.isNotBlank(centroCustos)) {
criteriaBuilder.and(criteriaBuilder.equal(root.get(VwReplPrevia_.codigoCentroCustos), centroCustos));
}
If that's not the problem, see which SQL query is generated in the logs by your JPA engine, and compare it with the native query to find what the difference is.