I am making board and now trying to make search function.
but values doesn't come out if I search keyword
I have tried to run on oracle with printed sql and parameter(optionText,searchText..) it worked fine but result set doesnt have value
public List<boardVO> getBoardList(String optionText,String searchText,int totalNum , int nowPage){
List<boardVO> list = new ArrayList<boardVO>();
try {
connectDB();
String sql = "select * from "
+ "(select rownum as rnum,recordno,userid,title,content,views,regdate from";
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
sql += " (select * from boardlist where ? like ?))";
}else{
sql += " boardlist)";
}
sql += "where rnum>=? and rnum<=? order by recordno desc";
pstmt = conn.prepareStatement(sql);
int finalNum = totalNum -(5*(nowPage-1));
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
pstmt.setString(1, optionText);
pstmt.setString(2, "%"+searchText+"%");
if(finalNum>4) {
pstmt.setInt(3, finalNum-4);
pstmt.setInt(4, finalNum);
}else {
pstmt.setInt(3, 1);
pstmt.setInt(4, finalNum);
}
}else {
pstmt.setInt(1, finalNum-4);
pstmt.setInt(2, finalNum);
}
rs = pstmt.executeQuery();
while(rs.next()) {
boardVO vo = new boardVO();
System.out.println("while");
vo.setRecordNo(rs.getInt(2));
vo.setUserid(rs.getString(3));
vo.setTitle(rs.getString(4));
vo.setContent(rs.getString(5));
/* System.out.println(vo.getContent()); */
vo.setViews(rs.getInt(6));
vo.setRegdate(rs.getString(7));
list.add(vo);
}
} catch (Exception e) {
System.out.println("get board list error");
e.printStackTrace();
}finally {
closeDB();
}
return list;
}
I think this is your problem:
(select * from boardlist where ? like ?)
It looks like you are trying to pass both a column name and a searchable value to your query: you can't do this with parameters. Both assignments will be treated as literals, so your executed code will be something like this:
select * from boardlist where 'COLUMN_NAME` like '%some string%'
Perfectly valid SQL, just won't return any results.
If this is the case you need to change the assemblage of the statement to include the column name ...
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
sql += " (select * from boardlist where " + optionText + " like ?))";
}else{
... and remove the parameter assignment:
if(optionText!=null && !optionText.equals("") && searchText!=null &&!searchText.equals("")) {
pstmt.setString(1, "%"+searchText+"%");
Related
I want to verify if my JDBC query output has data in it or not. If it doesn't contain any data then it should print the assertion as false.
I tried using this:
System.out.println("Table contains "+rs.getRow()+" rows");
if (!rs.next())
{
Assert.assertTrue(false);
}
else
{
Assert.assertTrue(true);
}
I tried using as below:
System.out.println("Table contains "+rs.getRow()+" rows");
if (!rs.next())
{
Assert.assertTrue(false);
}
else
{
Assert.assertTrue(true);
}
But it didn't work. So can anyone suggest how to solve this?
If you only need to know, how many rows are in a table, let the DBMS count them with:
select count(*) as noRows from table
And within your java code it will look like this snippet
boolean hasRows= false;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery("select count(*) as noRows from table");
if ( rs.next() ) {
if ( rs.getInt(1) > 0 ) {
hasRows = true;
}
}
} catch (SQLException sqlex ) {
// print or log an error message
} finally {
if ( rs != null ) {
try {
rs.close();
} catch (SQlException sqlex ) {
// print or log an error message
}
}
if ( stmt != null ) {
try {
stmt.close();
} catch (SQlException sqlex ) {
// print or log an error message
}
}
}
Assert.assertTrue(hasRows);
And it could also make sense to close your connection.
This will just return the rows within a table. If you need to know the size of a particular query, I for myself would do it similarly with the query and just replace the fields from the query with the count(*) or count(DISTINCT xyz) command. Try it first out within your sql monitor, because if the query runs to long, you might not be happy.
This is the correct example, which does not work:
If the LANGUAGE column is the same as the LANGUAGE COLUMN and the NLS_CLASS_NAME column is the same as the KEYWORD COLUMN
Given that they are true, if you noticed the language string I turned it into lowercase and I cut the string so that it becomes "en", since it was first ENG
You must print the language list, keyword is translation
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
I noticed that it takes a long time to start up, then it prints continuously but incorrectly, because it doesn't print the translation in the for loop.
Can you help me kindly?
//Traduzione in Db2 a SqlServer
public void getTraduzione() throws Exception {
List<DizioPt> listDizio = new ArrayList<DizioPt>();
List<ClassHdrNls> listHdr = new ArrayList<ClassHdrNls>();
String className = "";
String language = "";
String nlsClassName = "";
String lingua = "";
String keyword = "";
String traduzione = "";
Database database = new Database();
// Db2
Connection dbConnectionDb2 = null;
Statement statementDb2 = null;
// SqlServer
Connection dbConnectionSqlServer = null;
Statement statementSqlServer = null;
// Query Db2
String queryDb2 = "select * from THERA.CLASS_HDR_NLS WHERE
THERA.CLASS_HDR_NLS.LANGUAGE='en'";
// Query SqlServer
String querySqlServer = "select * from DIZIOPT WHERE
DIZIOPT.LINGUA='ENG'";
try {
// Connessione --> SqlServer
dbConnectionSqlServer = database.getConnectionSqlServer();
statementSqlServer = dbConnectionSqlServer.createStatement();
// Connessione -->Db2
dbConnectionDb2 = database.getConnectionDb2();
statementDb2 = dbConnectionDb2.createStatement();
// Risultato SqlServer
ResultSet rsSqlServer = statementSqlServer.executeQuery(querySqlServer);
// Risultato Db2
ResultSet rsDb2 = statementDb2.executeQuery(queryDb2);
while (rsSqlServer.next() && rsDb2.next()) {
ClassHdrNls classHdrNls = new ClassHdrNls();
className = rsDb2.getString("CLASS_NAME");
classHdrNls.setClassName(className);
language = rsDb2.getString("LANGUAGE");
classHdrNls.setLanguage(language);
nlsClassName = rsDb2.getString("NLS_CLASS_NAME");
classHdrNls.setNlsClassName(nlsClassName);
listHdr.add(classHdrNls);
DizioPt diziopt = new DizioPt();
lingua = rsSqlServer.getString("LINGUA");
diziopt.setLingua(lingua);
keyword = rsSqlServer.getString("KEYWORD");
diziopt.setKeyword(keyword);
traduzione = rsSqlServer.getString("TRADUZIONE");
diziopt.setTraduzione(traduzione);
listDizio.add(diziopt);
for (int i = 0; i < listHdr.size(); i++) {
for (int j = 0; j < listDizio.size(); j++) {
if (listHdr.get(i).getNlsClassName().equalsIgnoreCase(listDizio.get(j).getKeyword())
&& listHdr.get(i).getLanguage()
.equalsIgnoreCase(listDizio.get(j).getLingua().toLowerCase().substring(0, 2))) {
System.out.println("Class name: " + listHdr.get(i).getClassName());
System.out.println("Lingua: " + listHdr.get(i).getLanguage());
System.out.println("Testo: " + listHdr.get(i).getNlsClassName());
System.out.println("Traduzione: " + listDizio.get(j).getTraduzione());
}
}
}
}
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (statementDb2 != null && statementSqlServer != null) {
statementDb2.close();
statementSqlServer.close();
}
if (dbConnectionDb2 != null && dbConnectionSqlServer != null) {
dbConnectionDb2.close();
dbConnectionSqlServer.close();
}
}
}
I'm scanning my code with SonarQube and I'm getting the following bugs:
-A prepared statement is generated from a nonconstant String
-Nonconstant string passed to execute method on an SQL statement
I have an sql query to which I append based on some conditions.
Example:
PreparedStatement ps = null;
StringBuilder sql = new StringBuilder("UPDATE" + tableName + " SET some_field = ? WHERE a_field = a_value");
if (myObject.getField1() != null) {
sql.append(" AND Field1 = " + myObject.getField1());
}
if (myObject.getField2() != null) {
sql.append(" AND Field2 = " + myObject.getField2());
}
if (myObject.getField3() != null) {
sql.append(" AND Field3 = " + myObject.getField3());
}
if (myObject.getField4() != null) {
sql.append(" AND Field4 = " + myObject.getField4());
}
...
**ps = connection.prepareStatement(sql.toString());** //generating bug
if (myObject.getSomeField() == null) {
ps.setNull(1, nevermind);
} else {
ps.setString(1, myObject.getSomeField());
}
I tried passing a final String = sql.toString(); to the prepareStatement() function and it still generates the bug.
The issue that's being raised is that you're assembling your SQL command with concatenation: which table to update, which columns to set and what values to put in them.
You should find a way to hard code the table and columns and use parameter binding for the values.
There are many questions related to this topic, but I couldn't find a solution to my problem.
I have a table of "products" which I am trying to update in netbeans. The SQL statements works in SQL dev, and I have double checked my connection etc.
update products
set pvolume = 2, pprice = 15
where productid = 3;
output: 1 rows updated.
but running in netbeans it won't execute. If I have missed some small syntax issue I apologize, but I really need help with this method.
public boolean editProduct(int ID, String name, int volume, int quantity, String description, int price) {
boolean success = false;
Connection con = ConnectionTools.getInstance().getCurrentConnection();
String SQLString1 = "UPDATE products "
+ "SET pname = ?, "
+ "pvolume = ?, "
+ "pquantity = ?, "
+ "pdescription = ?, "
+ "pprice = ? "
+ "WHERE productID = ?";
PreparedStatement statement = null;
try {
statement = con.prepareStatement(SQLString1);
statement.setString(1, name);
statement.setInt(2,volume);
statement.setInt(3, quantity);
statement.setString(4, description);
statement.setInt(5, price);
statement.setInt(6, ID);
statement.executeUpdate();
success = true;
}catch (Exception e){
System.out.println("Insertion error!");
System.out.println(e.getMessage());
}finally {
try {
statement.close();
} catch (SQLException e) {
System.out.println("Statement close error!");
System.out.println(e.getMessage());
}
}
return success;
}
Running through the debug it seems to run through the try as far as statement.setInt(6, ID) but then does not execute. Here is the output:
Insertion error!
ORA-00971: missing SET keyword
Any help/advice would be appreciated! Thanks
You have to use brackets: update products set (pvolume = 2, pprice = 15) where productid = 3
Im trying to write a method which will allow me to search different DataTables, over different columns.
So far i have the following:
string selectedValue;
string searchColumn;
string targetColumn;
var results = (from a in dt.AsEnumerable()
where a.Field<string>(searchColumn) == selectedValue
select new
{
targetColumn = a.Field<string>(targetColumn)
}).Distinct();
Which kind of gets the job done, but I'm left with the column name as targetColumn rather than the actual column name I want.
Is there any way to resolve this?
Thanks in advance
CM
I make a LINQ to Datatables
public List<DataRow> Where(this DataTable dt, Func<DataRow, bool> pred)
{
List<DataRow> res = new List<DataRow>();
try {
if (dt != null && dt.Rows.Count > 0) {
for (i = 0; i <= dt.Rows.Count - 1; i++) {
if (pred(dt(i))) {
res.Add(dt(i));
}
}
}
} catch (Exception ex) {
PromptMsg(ex);
}
return res;
}
Usage :
var RowsList = dt.Where(f => f("SomeField").toString() == "SomeValue" ||
f("OtherField") > 5);