SQL Update in another class - java

Thanks for helping me out with my problem.
So I tried to insert a SQL Update using a method in a class named Functions, the main program doesn't give any error, and whenever I use the function, it just don't change anything in the SQL table after refreshing.
Here is my updateSQL method in class Functions :
public static void updateSQL(String sql, String updatenames[])
{
Connection connected = null;
PreparedStatement prepared = null;
connected = connexionmysql.connexionDB();
try
{
prepared = connected.prepareStatement(sql);
for(int i = 1; i < updatenames.length+1 ; i++) {
prepared.setString(i, updatenames[i-1]);
}
prepared.execute();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
And here is how I call this function in my main class :
String datan[] = { inputPASS, type1, inputEMAIL, inputNAME };
Functions.updateSQL("UPDATE users SET userPASS = ? ,userTYPE = ? ,userEMAIL = ? WHERE userNAME = ? ", datan);

I did solve the problem. The functions I did write are working as expected, but the problem was in the way I was calling the method.
Instead of calling the function in a static way, I was calling it in an "usual" way so Eclipse didn't give me any error in that line.

Related

Java SQL problem executing query through CallableStatement with parameter

I have a problem in a CallableStatement that execute a stored procedure query which accept a parameter.
I have a list of string that contains the query like:
{call query5_immatricolati(?)}
I have a list of string that contains the parameter like
String cds = "L-INF";
I have no SQL syntax error when I run but the result set doesn't have any value.
The expected result of the execution is that i could create an object by receiving data from the result set.
Here is the code:
for (int i = 0; i < INDICATORI.getInstance().getListaIndicatori().size();) {
for (int j = 0; j < INDICATORI.getInstance().getListaQuery().size();) {
if (INDICATORI.getInstance().getListaIndicatori().get(i).equals("iC00a")) {
for (String cds : CDS.getInstance().getCds().values()) {
ArrayList<indicatore> lista = new ArrayList<indicatore>();
String query = INDICATORI.getInstance().getListaQuery().get(j);
try {
CallableStatement cb = DB.getInstance().getConnection().prepareCall(query);
cb.setString(1, cds);
DB.getInstance().setResultSet(cb.executeQuery());
} catch (SQLException e) {
e.printStackTrace();
}
try {
while (DB.getInstance().getResultSet().next()) {
iC00a obj = new iC00a();
obj.setId(counter);
obj.setAnnoIscrizione(DB.getInstance().getResultSet().getString(1));
obj.setIscrittiPrimoAnno(DB.getInstance().getResultSet().getInt(2));
lista.add(obj);
counter++;
}
} catch (SQLException e) {
e.printStackTrace();
}
map.getInstance().getMap().put(INDICATORI.getInstance().getListaIndicatori().get(i)+cds, lista);
counter=0;
}
}
i++;
j++;
}
}
I tried to manually set in cb.setString(1,cds) the value like cb.setString(1,"L-INF") AND IT WORKS !!!
But I can't set manually the parameter, I need to iterate with for each loop each string and dynamically insert as parameter.
Why if I set the parameter manually like a string it works instead if i give a string variable not ?
Could anyone tell me what I'm doing wrong?
After a lot of attempts, I've found the solution.
The problem is in your variable cdsbecause it could have white spaces before or after.
Try:
cb.setString(1,cds.strip());
For me it worked.

Java returning null pointer exception for SQL query that gets passed to JSP

I am working on a school assignment that required us to use SQL statements in Java code as well as use the LIKE operator for a search. In order to properly search I have to get a string from the user, and split the string by any delimiter, and then run the query like so:
SELECT * FROM movies WHERE (movies.title LIKE '%userInput%');
I then return this query in the form of an ArrayList.
Now, when I was testing it out. I originally tested it with no user input, and my query became: SELECT * FROM movies WHERE (movies.title LIKE '%%');. This gave me the correct results.
However when I put a title in there, all of the sudden I get a NullPointerException on this line:
if(title.equals("")) { return "(movies.title LIKE '%%') "; from this section of my code:
public String getSearchString(String title) {
if(title.equals("")) { return "(movies.title LIKE '%%') "; }
String ret = "(";
ArrayList<String> titleArray = Util.splitSearch(title);
for(int i = 0; i < titleArray.size() - 1; ++i) {
String temp = titleArray.get(i);
String stmt = "movies.title LIKE '%" + temp + "%' OR ";
ret += stmt;
}
String temp = "movies.title LIKE '%" + titleArray.get(titleArray.size() - 1) + "%')";
ret += temp;
return ret;
}
This is then called like so:
public List<Movie> listMovies(String title) throws SQLException {
List<Movie> search = new ArrayList<Movie>();
if(null != title && title.isEmpty()) { title = ""; }
ResultSet res = queryMovies(getSearchString(title));
while(res.next()) {
Movie mov = new Movie();
mov.setTitle(res.getString("title"));
search.add(mov);
}
return search;
}
private static queryMovies(String st) throws SQLException {
ResultSet res = null;
try {
PreparedStatement ps = dbcon.prepareStatement(st);
res = ps.executeQuery();
} catch(SQLException e) {
e.printStackTrace();
}
return res;
}
I unfortunately have to do this since I won't know how much a user will enter. And I am also not allowed to use external libraries that make the formatting easier. For reference my Util.splitSearch(...) method looks like this. It should be retrieving anything that is a alphanumeric character and should be splitting on anything that is not alphanumeric:
public static ArrayList<String> splitSearch(String str) {
String[] strArray = str.split("[^a-zA-Z0-9']");
return new ArrayList(Arrays.asList(strArray));
}
What is interesting is when I pass in getSearchString(""); explicitly, I do not get a NullPointerException. It is only when I allows the variable title to be used do I get one. And I still get one when no string is entered.
Am I splitting the String wrong? Am I somehow giving SQL the wrong statement? Any help would be appreciated, as I am very new to this.
the "title" which is passed from input is null, hence you're getting nullpointerexception when you do title.equals("").
Best practices suggest you do a null check like (null != title && title.equals("")).
You can also do "".equals(title)

Challenging token error

I improved the structure after a good observation from [http://stackoverflow.com/users/1690199/v-k] I am still getting a token error even though the syntax looks correct to me. More comments and critiques will be useful and acknowledged here.
import de.bezier.data.sql.*;
PostgreSQL pgsql;
Float val;
void setup()
{
size( 100, 100 );
println(val);
}
Token error identified in Processing 2 at Class Database.
Class Database
{
String user = "user";
String pass = "pass";
String database = "db";
Float val;
Database (Float col) {
val = col;
}
void database_connection( col )
{
//sets up database
pgsql = new PostgreSQL( this, "127.0.0.1", database, user, pass );
if ( pgsql.connect() )
{
pgsql.query( "SELECT col FROM table ORDER BY col DESC LIMIT 1; " );
return( pgsql.getFloat("col") );
}
else
{
println ("failed to connect to the database");
}
}
}
OLD ISSUE: Class structure addressed after a great observation from [http://stackoverflow.com/users/1690199/v-k]
import de.bezier.data.sql.*;
.....
.....
Old code removed for clarity of this issue.
Classes don't take arguments. Also it is class not Class... Am i missing something? Look, a general sample:
class Database {
String user = "user";
String pass = "pass";
String database = "db";
float val; //by convention no Caps for vars...
// a constructor, which get partameters
Database (float v) {
val = v;
}
// a method
void database_setup() {
//whateverq
}
}//end of Database class
First, you should create a new question if you have a second question. Second, you never create the variable pgsql, you just start using it immediately. Move this line:
PostgreSQL pgsql;
to this group of lines:
String user = "user";
String pass = "pass";
String database = "db";
float val;
It's a variable that gets used in that class, so put it in that class. Also, use "float" with a lowercase "f" :)

Improve the search functionality

How can I improve the search functionality.? I have written some codes to search for something.The search was taking too much time. And the code snippets here,
I am pulling the data from the database using this method.,
OracleConnection connection = null;
OraclePreparedStatement ptmst = null;
OracleResultSet rs = null;
OracleCallableStatement cstmt = null;
StringBuffer strBfr = new StringBuffer();
ArrayList myList = new ArrayList();
try
{
connection = (OracleConnection) TransactionScope.getConnection();
strBfr.append("select distinct .......... ");
ptmst = (OraclePreparedStatement)connection.prepareStatement(strBfr.toString());
rs = (OracleResultSet)ptmst.executeQuery();
while (rs.next())
{
HashMap hashItems = new HashMap();
hashItems.put("first",rs.getString(1));
hashItems.put("second",rs.getString(2));
myList.add(hashItems);
}
}
catch (Exception e) {
}
finally {
try {
if (ptmst != null) {
ptmst.close();
}
} catch (Exception e) {
}
try {
if (connection != null) {
TransactionScope.releaseConnection(connection);
}
} catch (Exception e) {
}
}
return myList;
In my jsp:
ArrayList getValues = new ArrayList();
getValues = //calling Method here.
for(int i=0; i < getValues.size();i++)
{
HashMap quoteSrch=(HashMap)allPOV.get(i);
first = (String)quoteSrch.get("first");
second = (String)quoteSrch.get("second");
}
Query:
SELECT DISTINCT(mtl.segment1),
mtl.description ,
mtl.inventory_item_id ,
mtl.attribute16
FROM mtl_system_items_b mtl,
mtl_system_items_tl k
WHERE 1 =1
AND mtl.organization_id = ?
AND k.inventory_item_id = mtl.inventory_item_id
AND NVL(orderable_on_web_flag,'N')= 'Y'
AND NVL(web_status,'UNPUBLISHED') = 'PUBLISHED'
AND mtl.SEGMENT1 LIKE ? --Here is the search term
Make sure organization_id , inventory_item_id and especially SEGMENT1 is indexed in your table.
Your query is pretty standard , if that doesn't work then it seems like your DB server is responding slow which could be due to number of reasons like low space , low memory , slow disk/read etc.
You can then ask your DBA/Server admins to check that.
First you need to find out the real problem
Is it the DB query
Is it the Network (is the App and the DB located on the same machine?)
Once you have identified that it is the DB query, then it becomes more of a DB question.
How does the two tables look like?
Any index used?
How does the data look like (How many rows etc)
After you have analyzed this, you should be able to post the question differently and expect an answer. I am not a DB guy, but I am sure someone would be able to provide some pointers.
Tunning has to be done:
Check TransactionScope.getConnection(); is giving connection without any delay.
Instead of creating new HashMap hashItems = new HashMap(); you can use
while (rs.next()){
myList.add(rs.getString(1) + "delimiter" + rs.getString(2));
}
in jsp use
first = allPOV.get(i).split("delimter")[0];
second = allPOV.get(i).split("delimter")[1];
so that you can reduce memory.
If possible use limit in your query, and use index on SEGMENT1 link.

Why does the NetBeans Java debugger never reach this code?

I'm trying to debug a method in Java using NetBeans.
That method is:
public Integer getNumberOfClamps(Locations paLocation) {
Integer ret = -1;
List list = new ArrayList();
String removeme = "ABC";
if (paLocation == null) {
return ret;
}
try {
IO io = new IO(this.getSchemaName());
Session session = io.getSession();
String sql = "select count(*) from assets a join assettypes at on (at.id = a.assettype_id) ";
sql += "where a.currentlocation_id = " + paLocation.getId() + " and at.clamp = 1 and at.active = 1;";
list = session.createQuery(sql).list();
// for some reason, list is empty yet MySQL reports 40 records
// and the following two lines are never reached!
ret = list.size();
removeme = "WHAT???";
} catch (Exception ex) {
ret = -1; // explicitly set return
} finally {
return ret;
}
}
Towards the middle of the method you will see list = session.createQuery(sql).list();
For some reason, this is returning an empty list even though when the SQL is run manually, I get 40 results.
But the odd part is that once the .list() is called, it jumps to the finally block and never reaches the rest! So for testing, 'removeme' should equal WHAT??? but the debugger reports it as still ABC.
What gives?
You are using the wrong method. 'createQuery' is expecting HQL syntax. Change your method to 'createSQLQuery'

Categories