Unable to solve Java form of jdbc query with variables - jdbc

sql3 = "select avg(eff),min(eff),max(eff) from(select ("+baseParam+"/"+denom+"))as eff from ras)as s"; This is query whose output i want.
When i execute the code i get the error stating check your mysql version for syntax. I am using string to store the name of columns. I want to find the efficienccy with respect to 2000 Job_Render i.e. efficiency for each job_render. But what i get is total efficiency of all job_render. when i use the sql syntax with their direct column names. I have commented that query too for the reference. I want to find efficiency of each job render with respect to their 2000 JOBID. Bottom line is i want to find efficiency of 2000 JOBID each whose formula is Job_Render/LC_Final+LC_Preview. I have stored Job_Render in String baseParam and sum of both LC in String Denom. Please help me out.
public class Efficiency {
static final String DB_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/";
static final String DB_USER = "root";
static final String DB_PASSWORD = "root";
static final String dbName = "raas";
public static void main(String[] args) {
try{
effFunc();
}
catch (Exception q){
q.getMessage();
}
}
static void effFunc() throws ClassNotFoundException,SQLException{
Connection conn = null;
// STEP 2: Register JDBC driver
Class.forName(DB_DRIVER);
// STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_CONNECTION + dbName, DB_USER,
DB_PASSWORD);
System.out.println("Connected database successfully...");
String baseParam;
//String[] subParam ;
baseParam= "Job_Render";
String sql3="";
String denom="";
final String[] COL={ "LC_Final","LC_Preview"};
denom = "(" + COL[0] + "+" + COL[1] + ")";
Statement stmt = null;
stmt = conn.createStatement();
// sql3 = "select 'Efficiency' Field,avg(eff),min(eff),max(eff) from(select (Job_Render/(LC_Final+LC_Preview))as eff from ras)as s";
sql3 = "select avg(eff),min(eff),max(eff) from(select ("+baseParam+"/"+denom+"))as eff from ras)as s";
System.out.println(sql3);
//
try{
ResultSet res = stmt.executeQuery(sql3);
//System.out.println(res);
while(res.next()){
// String JobID = res.getString("JobID");
// System.out.println("Job ID : " + JobID);
String col1 = res.getString(1);
System.out.println(col1);
double avg = res.getDouble(2);
System.out.println("Average of eff is:"+avg);
double min = res.getDouble(3);
System.out.println("Min of eff is:"+min);
double max = res.getDouble(4);
System.out.println("Max of eff is:"+max);
}}
catch(Exception e){
e.getStackTrace();
System.out.println(e.getMessage());
}
}}

Your code runs the query sql1 which is the empty string,
String sql1="";
// sql1 = "select * from raas.jobs";
ResultSet res = stmt.executeQuery(sql1); // sql1 = ""
should be
ResultSet res = stmt.executeQuery(sql3);
Edit
Then to get the value(s)
String col1 = res.getString(1);
double avg = res.getDouble(2);
double min = res.getDouble(3);
double max = res.getDouble(4);

Related

syntax error, unexpected SYMBOL, expecting ',' while converting list to data.frame in R

Trying to convert java resultSet data to data.frame in R. Up to 5 rows no issue. But when more than 5 records are converting then getting the error "syntax error, unexpected SYMBOL, expecting ','"
public static void main(String[] args) throws ScriptException, FileNotFoundException {
RenjinScriptEngineFactory factory = new RenjinScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
engine.eval("source(\"script.R\")");
engine.eval("workflow.predict("+getData()+")");
}
public static ListVector getData() {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
StringArrayVector.Builder userid = new StringArrayVector.Builder();
StringArrayVector.Builder defaultCC = new StringArrayVector.Builder();
StringArrayVector.Builder typeId = new StringArrayVector.Builder();
StringArrayVector.Builder amount = new StringArrayVector.Builder();
StringArrayVector.Builder cc = new StringArrayVector.Builder();
StringArrayVector.Builder activity = new StringArrayVector.Builder();
try{
String query = "select top 6 wi.owner_user_id as userId, u.cost_center_id as defaultCC, li.expense_type_id typeId, wi.doc_specific_amount as amount, al.cost_center_id as cc,wi.activity_id as activity from alwf_work_item wi, alco_user u, aler_expense_line_item li,aler_line_allocation al where u.user_id = wi.owner_user_id and wi.business_object_id=li.parent_id and li.exp_line_item_id=al.exp_line_item_id";
connection = getConnection();
statement = connection.prepareStatement(query);
resultSet = statement.executeQuery();
while(resultSet.next()) {
userid.add(resultSet.getLong("userId"));
defaultCC.add(resultSet.getLong("defaultCC"));
typeId.add(resultSet.getLong("typeId"));
amount.add(resultSet.getLong("amount"));
cc.add(resultSet.getLong("cc"));
activity.add(resultSet.getLong("activity"));
}
}catch (Exception e) {
e.printStackTrace();
}
ListVector.NamedBuilder myDf = new ListVector.NamedBuilder();
myDf.setAttribute(Symbols.CLASS, StringVector.valueOf("data.frame"));
myDf.setAttribute(Symbols.ROW_NAMES, new RowNamesVector(userid.length()));
myDf.add("userId", userid.build());
myDf.add("defaultCC", defaultCC.build());
myDf.add("typeId", typeId.build());
myDf.add("amount", amount.build());
myDf.add("cc", cc.build());
myDf.add("activity", activity.build());
return myDf.build();
}
R Script
workflow.predict <- function(abc) {
print(abc)
print(data.frame(lapply(abc, as.character), stringsAsFactors=FALSE))
dataset = data.frame(lapply(abc, as.character), stringsAsFactors=FALSE)
library(randomForest)
classifier = randomForest(x = dataset[-6], y = as.factor(dataset$activity))
new.data=c(62020,3141877,46013,950,3141877)
y_pred = predict(classifier, newdata = new.data)
print(y_pred)
return(y_pred)
}
Below are the errors while running the script with top 6 records. But for top 5 records it is running without any error. Thanks in advance.
Exception in thread "main" org.renjin.parser.ParseException: Syntax error at 1 68 1 70 68 70: syntax error, unexpected SYMBOL, expecting ','
at org.renjin.parser.RParser.parseAll(RParser.java:146)
at org.renjin.parser.RParser.parseSource(RParser.java:69)
at org.renjin.parser.RParser.parseSource(RParser.java:122)
at org.renjin.parser.RParser.parseSource(RParser.java:129)
at org.renjin.script.RenjinScriptEngine.eval(RenjinScriptEngine.java:127)
at RTest.main(RTest.java:27)
Sample Data of the resultset is here
By using Builder userid = new ListVector.Builder() instead of StringArrayVector.Builder userid = new StringArrayVector.Builder() it is accepting more records without any error. I am not sure why StringArrayVector it is restricting to 5 records only.

Problem two query db2 sqlserver is not print output

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();
}
}
}

oracle jdbc driver reports no primary key columns on a table that has a primary key

This was reported by HibernateTools Reverse Engineering, but it seems to be true.
oracle jdbc driver reports no primary key columns on a table that has a primary key.
#Test
public void checkTable() throws SQLException, IOException {
System.out.println("in check table");
assertNotNull(conn);
Statement s = conn.createStatement();
ResultSet rset = s.executeQuery("select user from dual");
rset.next();
String username = rset.getString(1);
rset.close();
try {
s.execute("drop table " + username + ".x");
} catch (Exception e) {
// nothing it might not exist
}
s.execute("create table " + username + ".x (y number)");
s.execute("alter table x add constraint x_pk primary key (y)");
DatabaseMetaData meta = conn.getMetaData();
final String[] tableTypes = new String[] { "TABLE", "VIEW" };
ResultSet rs = meta.getTables(null, username, "X",tableTypes);
rs.next();
String table = rs.getString("table_name");
System.out.println("table is " + table);
rs.close();
rs = s.executeQuery("select * from user_constraints where table_name = 'X'");
rs.next();
String type = rs.getString("constraint_type");
assertEquals("P",type); // primary key
rs.close();
rs = meta.getPrimaryKeys(null, username, "X");
rs.next();
logger.info("getting pk");
System.out.print("wtf");
int colCount = 0;
while (rs.next()) {
final String pkName = rs.getString("pk_name");
logger.info("pkName: {}", pkName);
int keySeq = rs.getShort("key_seq"); // TODO should probably be column seq
String columnName = rs.getString("column_name");
logger.warn("seq: {}, columnName: {}, keySeq, columnName");
colCount++;
}
System.out.println("colCount: " + colCount);
assertEquals(1,colCount);
}

SQL prepared statement not taking '?' on both sides of where clause

I have something like this in my sql query
private static final String QUERY_PHYSICIAN_INFO= "SELECT * FROM PHYSICIAN_INFO WHERE ? = ?";
but following is not working..
Connection conn = null;
PreparedStatement stmt = null;
String logintype;
if(isInteger(id))
{
logintype="BADGEID";
}else{
logintype="ID";
}
stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO);
stmt.setString(1, logintype);
stmt.setString(2, id);
ResultSet rs = stmt.executeQuery();
Physician phs = null;
Is there any special reason for this?
Thanks in advance.
? is for passing parameters, not field names.
If you must do this, build the SQL as
"SELECT * FROM PHYSICIAN_INFO WHERE " + "BADGEID" + " = ?"
You could try something like this because ? can be used only for passing parameters or you could use a database function and then pass values to the function.
private static final String QUERY_PHYSICIAN_INFO_BADGE= "SELECT * FROM PHYSICIAN_INFO WHERE BADGEID = ?";
private static final String QUERY_PHYSICIAN_INFO_ID= "SELECT * FROM PHYSICIAN_INFO WHERE ID = ?";
Connection conn = null;
PreparedStatement stmt = null;
String logintype;
if(isInteger(id))
{
stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO_BADGE);
}else{
stmt=conn.prepareStatement(QUERY_PHYSICIAN_INFO_ID);
}
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
Physician phs = null;

Spring JDBC Framework Conditional Prepared Statement

public ResultSet getAdCampaignDetailsbyName(ADCampaignDetails Obj,
Connection conn, ResultSet rs, PreparedStatement pstmt) throws SQLException {
String query = "select adCampaignName,adCampaignId from AdCampaignDetails";
query += " where 1=1 ";
if (Obj.getAdCamapignName() != null)
query += " and adCampaignName = ?";
if (Obj.userId != "")
query += " and userId = ?";
pstmt = conn.prepareStatement(query);
int i = 0;
if (Obj.getAdCamapignName() != null)
pstmt.setString(++i, Obj.getAdCamapignName());
if (Obj.userId != "")
pstmt.setString(++i, Obj.userId);
System.out.println(" Q : " + query);
rs = pstmt.executeQuery();
return rs;
}
I am new to Spring , in this above query, i have used two conditions , How to execute query with condition in Spring JDBC Framework?
You can use SimpleJDBCTemplate.
// SQL query
String query = "select adCampaignName,adCampaignId from AdCampaignDetails where 1=1";
// Map with parameter value
Map<String, Object> parameters = new HashMap<String, Object>();
if (adCampaignName!=null){
parameters.put("adCampaignName ", adCampaignName );
query += " AND adCampaignName = :adCampaignName";
}
if (userId!=null){
parameters.put("userId", 1);
query += " AND userId= :userId";
}
// Execute query using simpleJDBC Template
List<AdCampaignDetails> resultList = getSimpleJdbcTemplate().query(query, new customRowMapper(), parameters);
You can build the query string accordingly, just add coresponding entries in map.
Check this link for details.

Resources