Following is my code which retrieves Rally data.
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "examplehost";
String username = "exampleuser";
String password = "password";
String projectRef = "project";
String workspaceRef = "workspace";
String applicationName = "";
int queryLimit = 4000;
Connection conn = null;
String propertiesFile = "";
String projectValue = "";
String columnValue = "";
String returnValue = "";
RallyRestApi restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion());
try{
QueryRequest projectRequest = new QueryRequest("Project");
projectRequest.setFetch(new Fetch("Name", "TeamMembers"));
projectRequest.setWorkspace(workspaceRef);
projectRequest.setProject(projectRef);
projectRequest.setScopedDown(true);
projectRequest.setQueryFilter(new QueryFilter("Name", "contains", "DT-"));
projectRequest.setLimit(queryLimit);
QueryResponse projectQueryResponse = restApi.query(projectRequest);
int count = projectQueryResponse.getResults().size();
System.out.println(count);
if(count > 0){
for (int i=0;i<count;i++){
JsonObject projectObject = projectQueryResponse.getResults().get(i).getAsJsonObject();
JsonObject obj = projectObject.getAsJsonObject();
projectValue = JsonUtil.getJsonValue(obj, "_refObjectName");
System.out.println("Project: " + projectValue);
int numberOfTeamMembers = projectObject.getAsJsonObject("TeamMembers").get("Count").getAsInt();
if(numberOfTeamMembers > 0) {
QueryRequest teamRequest = new QueryRequest(projectObject.getAsJsonObject("TeamMembers"));
JsonArray teammates = restApi.query(teamRequest).getResults();
//JsonObject teammates = restApi.query(teamRequest).getResults();
if (teammates instanceof JsonArray) {
JsonArray jsonarr = teammates.getAsJsonArray();
//returnValue += squote;
for (int j=0; j<jsonarr.size(); j++) {
if (j>0)
returnValue += "\n";
JsonObject tobj = jsonarr.get(j).getAsJsonObject();
if (obj.has("Name"))
columnValue = getJsonValue(tobj, "Name");
if (obj.has("_refObjectName"))
columnValue = JsonUtil.getJsonValue(tobj, "_refObjectName");
returnValue += columnValue;
System.out.println(columnValue);
}
//returnValue += squote;
}
//columnValue = JsonUtil.getJsonString(teammates);
//for (int j=0;j<numberOfTeamMembers;j++){
//JsonObject teamObject = teamQueryResponse.getResults().get(j).getAsJsonObject();
//System.out.println(teammates.get(j).getAsJsonObject().get("_refObjectName").getAsString());
//}
}
}
}
}catch(Exception e){
e.printStackTrace();
} finally{
restApi.close();
}
}
I'm trying to insert Project ID and the associated team members into db. For one Project ID there may be 1- 10 members, The count may differ for each project. In DB, there would be only two Column holding Project ID and User name. Could anyone help me with this request?
Hope it helps.
If you need more details, please do reply
Thanks
Sreer
From your comment above, the actual line that is failing is:
st.executeUpdate("INSERT INTO CUST_RALLY_TEAM_MEMBER " + "VALUES projectValue,columnValue)");
Here, you are literally passing this string to Oracle:
INSERT INTO CUST_RALLY_TEAM_MEMBER VALUES projectValue,columnValue)
You need to pass the values of those variables (you're also missing an open parenthesis:
st.executeUpdate("INSERT INTO CUST_RALLY_TEAM_MEMBER VALUES ('" + projectValue + "','" + columnValue + "')");
This assumes that the cust_rally_team_member contains only these two columns, if not (and as a best practice, even if it does), you should be specifying the columns to be inserted into. Assuming the column names are also "projectvalue" and "columnvalue", then the statement would be:
st.executeUpdate("INSERT INTO CUST_RALLY_TEAM_MEMBER (projectvalue,columnvalue) VALUES ('" + projectValue + "','" + columnValue + "')");
Note, too, that prepared statements are a good approach for a process such as this. It eliminates the risk of SQL errors if the values contain a single quote, reduces the risk of SQL Injection attacks, and improves performance by compiling the statement only once.
Related
I am using Java 11 JDBC and MySQL Connector/J 8 jar. All other CRUDs are running OK, but when I am trying to run SET foreign_key_checks = 0 or SET foreign_key_checks = 1, it shows syntax error with SQLState: 42000 and VendorError: 1064. So if there is any way to run such queries using JDBC?
try {
Statement checks = connection.createStatement();
checks.execute("set foreign_key_checks=0");
checks.close();
String tableName = json.getString("table");
RowOperation rowOperation = RowOperation.valueOf(json.getString("activity"));
JSONArray rows = json.getJSONArray("rows");
for (Object obj : rows) {
JSONObject row = (JSONObject) obj;
List<String> keys = new ArrayList<>(row.keySet());
StringBuilder sb = new StringBuilder();
String columns = keys.stream().collect(Collectors.joining(",")) + ",rowOperation,rowCreatedOn";
String questionMakrs = keys.stream().map(x -> "?").collect(Collectors.joining(",")) + ",?,?";
String query = "insert into " + tableName + " (" + columns + ") values (" + questionMakrs + "); SET FOREIGN_KEY_CHECKS=0";
PreparedStatement stmt = connection.prepareStatement(query);
int i = 0;
for (i = 0; i < keys.size(); i++) {
String key = keys.get(i);
stmt.setString(i + 1, String.valueOf(row.get(key)));
}
stmt.setString(i + 1, rowOperation.name());
i++;
stmt.setTimestamp(i + 1, Timestamp.valueOf(LocalDateTime.now()));
stmt.execute();
stmt.close();
}
} finally {
Statement checks = connection.createStatement();
checks.execute("set foreign_key_checks=1");
checks.close();
}
You are trying to execute two statements, an INSERT followed by a SET, separated by a semicolon, in a single call to prepareStatement().
https://dev.mysql.com/doc/refman/8.0/en/sql-prepared-statements.html
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).
You must execute the SET statement in a separate statement.
I'm working a project(Full source code here) and as part of the project, I've created a Database class to make interfacing with the SQLite database easier and cleaner. I'm currently attempting to write a method that will use SELECT along with the given parameters to return a string array containing the results. The issue that I'm having is that when I run the program to test it, Eclipse throws java.sql.SQLException: no such column: 'MOVES'
But, when I look at the database in a GUI, it clearly shows the column that I'm trying to access, and when I execute just the sql in the same program, it's able to return the data.
This is the method that I've written so far:
public String[] get(String what, String table, String[] conds) {
try {
if (what.equals("*")) {
throw new Exception("'*' selector not supported");
}
c.setAutoCommit(false);
stmt = c.createStatement();
String sql = "SELECT " + what.toUpperCase() + " FROM " + table.toUpperCase();
if (conds.length > 0) {
sql += " where ";
for (int i = 0; i < conds.length; i++) {
if (i == conds.length - 1) {
sql += conds[i];
break;
}
sql += conds[i] + " AND ";
}
}
sql += ";";
System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
if (table.toUpperCase().equals("DEX")) {
String id = "";//rs.getInt("id") + "";
String species = rs.getString("species");
String type1 = rs.getString("type1");
String type2 = rs.getString("type2");
String hp = rs.getInt("hp") + "";
String atk = rs.getInt("atk") + "";
String def = rs.getInt("def") + "";
String spa = rs.getInt("spa") + "";
String spd = rs.getInt("spd") + "";
String spe = rs.getInt("spe") + "";
String ab1 = rs.getString("ab1");
String ab2 = rs.getString("ab2");
String hab = rs.getString("hab");
String weight = rs.getString("weight");
return new String[] { id, species, type1, type2, hp, atk, def, spa, spd, spe, ab1, ab2, hab,
weight };
} else if (table.toUpperCase().equals("MOVES")) {
String name = rs.getString("NAME");
String flags = rs.getString("FLAGS");
String type = rs.getString("TYPE");
String full = rs.getString("LONG");
String abbr = rs.getString("SHORT");
String acc = rs.getInt("ACCURACY") + "";
String base = rs.getInt("BASE") + "";
String category = rs.getInt("CATEGORY") + "";
String pp = rs.getInt("PP") + "";
String priority = rs.getInt("PRIORITY") + "";
String viable = rs.getInt("VIABLE") + "";
return new String[] { name, acc, base, category, pp, priority, flags, type, full, abbr, viable };
} else if (table.toUpperCase().equals("LEARNSETS")) {
String species = rs.getString("SPECIES");
String moves = rs.getString("MOVES");
return new String[] { species, moves };
} else {
throw new Exception("Table not found");
}
}
rs.close();
stmt.close();
c.close();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
return null;
}
Screencaps:
UPDATE:
I wanted to double-check that the database viewer I was using wasn't messed up, so I opened up the terminal and ran
sqlite3 git/Pokemon/data.db
pragma table_info(MOVES);
Receiving this in response:
0|SPECIES|TEXT|0||0
1|MOVES|TEXT|0||0
Finally figured it out, for anybody else having this issue, make sure that the data you're trying to get from the result set is actually included in it. For example, if I call SELECT SPECIES FROM DEX; the result set won't contain other things like id, type, or any of those other columns, it will ONLY contain the species column. I'm not sure why it took me so long to figure this out, but there you have it.
Hey im attempting to to make an invoice program that uses Java and Sqlite as a database. I know that sqlite is a forward only language, but is there a way to scroll backwards or make it type scroll insensitive here is the class that im trying to use. I am attempting to put all of my information extracted from my database into an array.
public String[] getRow(int rowID)
{
String id =("");
String name = ("");
String day = ("");
String location = ("");
String price = ("");
String timestart= ("");
String Timeend = ("");
String Showtype = ("");
String[] row= new String[8];
try
{
Class.forName("org.sqlite.JDBC");
Connection x=DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stmt = x.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery ("SELECT ID, NAME, day, Location, price, timestart, Timeend, Showtype FROM Showinformation ORDER BY ID LIMIT 5 OFFSET:index;");
rs.step(rowID);
while(rs.next())
{
for(int i=0; i<8; i++)
{
id = rs.getString("ID");
row[0]=id;
name = rs.getString("NAME");
row[1]=name;
day = rs.getString("day");
row[2]=day;
location = rs.getString("Location");
row[3]=location;
price = rs.getString("price");
row[4]=price;
timestart= rs.getString("timestart");
row[5]=timestart;
Timeend= rs.getString("Timeend");
row[6]=Timeend;
Showtype= rs.getString("Showtype");
row[7]=Showtype;
}
//String potato =(i+1+id+""+name+""+day+""+location+""+price+""+timestart+""+Timeend+""+Showtype);
//System.out.println("ID = " + id +"\nNAME = " + name+"\nDAY = " + day+"\nADDRESS = " + location+"\nPRICE = " + price+"\nTIME START = " + timestart+"\nTIME END = " + Timeend+"\nSHOWTYPE = " + Showtype );
}
}
catch(Exception er)
{
System.err.println(er.getClass().getName()+":"+er.getMessage() );
}
return row;
}
any help would be appreciated.
Here is a method that I am writing for a class. It is supposed to refresh a table with data obtained from quering a database. I get an error when trying to scan through the line newResult.next().
I tried debugging, but that doesn't show me anything. the code prints out the line "In while loop", so I know that the problem is the in the line right after it. I constantly get the error, "After start of result set". I tried looking at my code, but it doesn't look like I am calling that method anywhere else either. thanks.
public void refresh()
{
try
{
Statement statement = gtPort.getConnection().createStatement();
//this query is also not working, not really sure how it works.
String query = "SELECT CRN, Title, Instructor, Time, Day, Location, Letter"
+ "FROM Section S WHERE CRN NOT IN "
+ "(SELECT CRN FROM Registers R WHERE Username = \""
+ gtPort.userName + "\")";
System.out.println(query);
statement.executeQuery(query);
System.out.println("Statemetne execute ");
// String[] columns = {"Select", "CRN", "Title", "Instructor", "Time",
// "Days", "location", "Course Code*", "Section"*,"Mode of Grading*"};
ResultSet result = statement.getResultSet();
System.out.println("created result");
data = new Object[10][10];
System.out.println("created data");
Object[] values = new Object[10];
System.out.println("created values");
// values[0] = null;
if (result == null)
{
System.out.println("result is null");
}
String[] titles = new String[100];
//for (int i = 1; i< table.getColumnCount(); i++)
//model.removeRow(i);
//table.removeAll();
//table.repaint()
model.setRowCount(0);
table = new JTable(model);
model.setRowCount(35);
for (int i = 1; result.next(); i++)
{
values[1] = Boolean.FALSE;
for (int j = 2; j< 8; j++)
values[j] = result.getString(j);
titles[i] = result.getString(2);
model.insertRow(i, values);
}
String[] codes = new String[table.getColumnCount()];
System.out.println("count: " + titles.length);
for (int i = 1; I < titles.length; i++)
{
query = new String("SELECT C.Code FROM Code C WHERE C.Title = \""
+ titles[i] + "\"");
//this is a different query to check for titles.
statement.executeQuery(query);
System.out.println(query);
ResultSet newResult = statement.getResultSet();
// codes[i] = newResult.getString(1);
if (newResult == null)
{
System.out.println("it is null");
break;
}
//this is the loop where it breaks.
while(newResult.next());
{
System.out.println("in while loop");
//this line prints, so the next line must be the problem.
model.setValueAt(newResult.getString(1), i, 8);
}
System.out.println("nr: \t" +newResult.getString(1));
}
System.out.println("before table");
table = new JTable(model);
System.out.println("created table");
}
catch (Exception exe)
{
System.out.println("errored in course selection");
System.out.println(exe);
}
}
Write ResultSet rs = statement.executeQuery(query); instead. getResultSet() is called when you have got more then one result sets from executed statement.
Don't use constructor new String() for creating String. Simply write:
String new = "content";
You cannot predict how much your first query will return so don't create arrays with stated size but use better ArrayList:
Code:
//creation
List<Object> values = new ArrayList<Object>();
List<String> titles = new ArrayList<String>();
//usage - adding
values.add(someObject);
//usage - getting
for (String title : titles)
//or
titles.get(byIndex);
I have a webservice where from the Client-side some parameters are passed to perform a query on the DB, the Server-Side is supposed to carry out the query and return the results.Since the result might be more than one row and i will have to use it on the client-side to show an output this what i did:
1.Perform the query
2.take each row of the result and put it in an array
3.convert the array to String and pass it to the client side(converted array to String, because it was simple)
BUT the problem is that it doesnt pass the the array-turned-string but only the value which was used to initialize the string, here is the code
String ris = "";
String q;
String beta = null;
String one="";
String errore = connetti();
try {
if (errore.equals("")) {
Statement st = conn.createStatement();
//ESECUZIONE QUERY
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
//This is the part which i'm talking about
else {
//getRowCount is another class used to find out number of rows,I use it to declare an array which would contain the result of the query
int two=getRowCount(rs);
String[] alpha= new String[two];
//Loop through the resultstatement and put result from the column **nome** in the array **alpha**
while(rs.next()){
alpha[i]=rs.getString("nome");
i++;
}
//The value of ris which is empty, is returned
ris="";
//instead of this one, where i convert the array **alpha** to String
ris=arrayToString(alpha,",");
}
}
else {
ris = errore;
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
}
//returns the number of rows of **ris**
public static int getRowCount(ResultSet set) throws SQLException
{
int rowCount;
int currentRow = set.getRow(); // Get current row
rowCount = set.last() ? set.getRow() : 0; // Determine number of rows
if (currentRow == 0) // If there was no current row
set.beforeFirst(); // We want next() to go to first row
else // If there WAS a current row
set.absolute(currentRow); // Restore it
return rowCount;
}
//converts the array to String
public String arrayToString(String[] array, String delimiter) {
StringBuilder arTostr = new StringBuilder();
if (array.length > 0) {
arTostr.append(array[0]);
for (int i=1; i<array.length; i++) {
arTostr.append(delimiter);
arTostr.append(array[i]);
}
}
return arTostr.toString();
Thanks alot in advance!
After conn.close() you return beta instead of ris. This may be the cause of the behavior you are experiencing. However, I am not sure because I can not properly see how you open and close the curly brackets.