I have a static query as Select * from Emp where Empid in (?) and I have that value of (?). I am not able to place that value. Please guide me. Let me know, I f anything else is required.
Try this java code:
public boolean yourMethod(String yuorValue) {
String sql = "select * from user where fieldName = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, yuorValue);//fieldvalue(1), Your passing value
ResultSet rs = stmt.executeQuery();
return rs.next();
}
Related
I am using Java 8 and oracle.
I have confirmed that this code is working:
Statement stmt = null;
String query = "select * from custref";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String cName = rs.getString("CUSTOMER_NAME");
System.out.println(cName);
}
When I change it to this, it does not give any results:
PreparedStatement prepStmt = null;
String query = "select * from custref where CUSTOMER_NUMBER = ?";
prepStmt = con.prepareStatement(query);
prepStmt.setString(1, "12344321");
ResultSet rs = prepStmt.executeQuery();
while (rs.next()) {
String cName = rs.getString("CUSTOMER_NAME");
System.out.println(cName);
}
I have confirmed that my data type is VARCHAR hence the set string. I know my connections are fine because the basic search works just when I switch to parameterized it doesn't fail or throw exceptions it just doesn't have a result set. I have also tried the :customerNumber convention instead of the ? and this didn't work either. This is quite embarrassing but I am at my end here, nothing I can find seems to address this.
I have a typical crosstab query with static parameters. It works fine with createStatement. I want to use preparestatement to query instead.
String query = "SELECT * FROM crosstab(
'SELECT rowid, a_name, value
FROM test WHERE a_name = ''att2''
OR a_name = ''att3''
ORDER BY 1,2'
) AS ct(row_name text, category_1 text, category_2 text, category_3 text);";
PreparedStatement stat = conn.prepareStatement(query);
ResultSet rs = stat.getResultSet();
stat.executeQuery(query);
rs = stat.getResultSet();
while (rs.next()) {
//TODO
}
But it does not seem to work.
I get a PSQLException -
Can't use query methods that take a query string on a PreparedStatement.
Any ideas what I am missing?
You have fallen for the confusing type hierarchy of PreparedStatement extends Statement:
PreparedStatement has the same execute*(String) methods like Statement, but they're not supposed to be used, just use the parameterless execute*() methods of PreparedStatement --- you already have given the actual query string to execute using conn.prepareStatement().
Please try:
String query = "...";
PreparedStatement stat = conn.prepareStatement(query);
ResultSet rs = stat.executeQuery();
while (rs.next()) {
// TODO
}
The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code
I have a database with the following layout
databasename:macfast
table name:users
columns
id,
user_name,
password,
fullName
I want to retrieve all the values from the column user_name and check each values with another one string which is already retrieved from a TEXTFIELD.But I can't(NullpointerException). Please help me.
public void deleteFclty() {
PreparedStatement stmt = null;
ResultSet rs = null;
String username=removeText.getText();
String qry = "SELECT user_name From users ";
try {
stmt = (PreparedStatement) connection.prepareStatement(qry);
rs = stmt.executeQuery();
while (rs.next()) {
String check=(rs.getString("user_name"));
System.out.println(check);
if(check.equals(username)){
Util.showErrorMessageDialog("EQUAL");
}else{
Util.showErrorMessageDialog("NOT EQUAL");
}
}
}catch (SQLException ex) {
Logger.getLogger(RemoveFaculty.class.getName()).log(Level.SEVERE, null, ex);
}
}
Problem is with the prepared statement (you don't put id into statement, which should be there instead of question mark).
Also I would recommend to do condition as "username.equals(check)", that can prevent null pointer exception.
"SELECT user_name From users where id=?"
This query has a parameter and you're not setting any value to it. Use PreparedStatement#setInt() or similar to set it, e.g.:
stmt.setInt(1, 1);
The problem is with PreparedStatement as you are using Question mark ? in your query for that you have to set the Id value.
String qry = "SELECT user_name From users where id=?";
stmt = (PreparedStatement) connection.prepareStatement(qry);
stmt.setInt(1,1001);
rs = stmt.executeQuery();
For your question in comment below:
List<String> values = new ArrayList();
while (rs.next()) {
values.add(0,rs.getString(<>))
}
// here do whatever you want to do...
// for example
for ( String value: values )
{
// check if value == TEXTFIELD
// if true then do something..
// else don't do anything
}
I did an experiment with a table having a VARCHAR column with null values trying to get the number of rows that have a specific column NULL. I used three forms:
form A
SELECT COUNT(*) FROM buyers WHERE buye_resp IS NULL
form B
SELECT COUNT(*) FROM buyers WHERE buye_resp = ?
... where the parameter is provided with setString(1, null)
form C
... like form B but the parameter is set with setNull(1, java.sql.Types.VARCHAR)
Of the three forms, only form A produced the correct result, forms B and C both returned 0 (code of the three forms at the end of the post). Which begs the question: what's the purpose of setNull?
The tests where run against a PostgreSQL 9.2 database.
code
private static int numOfRows_formA(Connection conn) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String pstmStr = "SELECT COUNT(*) FROM buyers WHERE buye_resp IS NULL";
pstm = conn.prepareStatement(pstmStr);
rs = pstm.executeQuery();
rs.next();
return rs.getInt(1);
} finally {
DbUtils.closeQuietly(null, pstm, rs);
}
}
private static int numOfRows_formB(Connection conn) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String pstmStr = "SELECT COUNT(*) FROM buyers WHERE buye_resp = ?";
pstm = conn.prepareStatement(pstmStr);
pstm.setString(1, null);
rs = pstm.executeQuery();
rs.next();
return rs.getInt(1);
} finally {
DbUtils.closeQuietly(null, pstm, rs);
}
}
private static int numOfRows_formC(Connection conn) throws SQLException {
PreparedStatement pstm = null;
ResultSet rs = null;
try {
String pstmStr = "SELECT COUNT(*) FROM buyers WHERE buye_resp = ?";
pstm = conn.prepareStatement(pstmStr);
pstm.setNull(1, java.sql.Types.VARCHAR);
rs = pstm.executeQuery();
rs.next();
return rs.getInt(1);
} finally {
DbUtils.closeQuietly(null, pstm, rs);
}
}
SQL uses ternary logic, therefore buye_responsible = ? always returns unknown (and never true) when buye_responsible is null. That's why you need IS NULL to check for null.
setNull() can be used, for example, when you need to pass nulls to INSERT and UPDATE statements. Since methods such as setInt() and setLong() take primitive types (int, long) you need a special method to pass null in this case.
In data base system a null is not equal to another null so
the line SELECT COUNT(*) FROM vat_refund.er_buyers WHERE buye_responsible = null won't return any record. The setNull() method simply set a null at the index position.Sets the designated parameter to SQL NULL. This from the JAVA API. That is it will set a SQL null for that index, but it don't use isNull() function as desired by you.
So that is why for form C also you are not getting any result.