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.
Related
I am using a mysql table, and now I need to compare a columns all values with a given String.
I want to check if all values of the result set matches with encryptedString.
Need to understand what result set does and how it works.
Here I have a method, Some variables, and 2 mysql queries.
final String secretKey = "!!!!";
String name = jText.getText();
String pass = jTextPass.getText();
String originalString = pass;
String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;
PreparedStatement PS;
ResultSet result;
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` =?";
PreparedStatement ps;
String query;
query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`=?";
try {
PS = MyConnection.getConnection().prepareStatement(query1);
PS.setString(1, name);
PS.setString(2, encryptedString);
rs = PS.executeQuery();
//while(result.next() ){
//I am not understanding what to do here.
ps = MyConnection.getConnection().prepareStatement(query);
ps.setString(1, encryptedString);
ps.setString(2, name);
ps.executeUpdate();
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
this.dispose();
//}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
}
First tip: using try-with-resources closes statement and result set even on exception or return. This also reduces the number of variable names for them because of the smaller scopes. This return from the innermost block I utilized. For unique names one can use if-next instead of while-next. A fail-fast by not just logging the exception is indeed also better; you can exchange the checked exception with a runtime exception as below, so it easier on coding.
String query1 = "SELECT `pass` FROM `Remember_Pass` WHERE `name` = ?";
String query = "UPDATE `tutor profile` SET `pass`=? WHERE `name`= ?";
try (PreparedStatement selectPS = MyConnection.getConnection().prepareStatement(query1)) {}
selectPS.setString(1, name);
//selectPS.setString(2, encryptedString);
try (ResultSet rs = selectPS.executeQuery()) {}
if (result.next()){ // Assuming `name` is unique.
String pass = rs.getString(1);
try (PreparedStatement ps = MyConnection.getConnection().prepareStatement(query)) {
ps.setString(1, encryptedString);
ps.setString(2, name);
int updateCount = ps.executeUpdate();
if (updateCount == 1) {
PassSuccess success = new PassSuccess();
success.setVisible(true);
success.pack();
success.setLocationRelativeTo(null);
return success;
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ForgetPassT.class.getName()).log(Level.SEVERE, null, ex);
throw new IllegalStateException(e);
} finally {
dispose();
}
the ResultSet object contains all the information about the query that you perform, it will contain all columns. In your code the result variable will return anything since there is no part in your code where is executed, to do this you have to...
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
while(result.next()){
String column1 = result.getString("columnName");
}
The result.next() method is a boolean method that says if the ResultSet object still have values of the table inside and it will continue until it reaches the last row that your SELECT statement retrives. Now if you want to match the value of some column with other variables you can do it inside the while(result.next()).
result.getString("columnName") will extract the value from columnName as a String.
If you want to save things in an ArrayList to save the data and then use this list as you want the code can be like...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
List<Object> data = new ArrayList();
while(result.next()){
data.add(result.getString("columnName"));
}
return data;
Obviously you have to change the Object with the type of things that you want to store in the List.
Or if you want to store the data in an array. As I said in my comment this won't be dinamic, but...:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
String[] data = new String[NUMBER_OF_COLUMNS_IN_RESULTSET];
while(result.next()){
data[0] = result.getString("columnName1");
data[1] = result.getString("columnName2");
data[2] = result.getString("columnName3");
//And so on...
}
return data;
The other way is that if you are returning an entity you can set the values of the ResultSet directly in the POJO:
Statement statement = MyConnection.getConnection().createStatement();
ResultSet result = statement.executeQuery("YOUR SELECT STATEMENT HERE");
Entity entity = new Entity();
while(result.next()){
entity.setColumnName1(result.getString("columnName1"));
entity.setColumnName2(result.getString("columnName2"));
entity.setColumnName3(result.getString("columnName3"));
//And so on...
}
return entity;
There are so many ways to store the data, just ask yourself how do you want to receive the data in the other parts of you code.
Regards.
I am facing problem with updating column value by resultset in mariadb from java code. Looks like resultset.updateString() method is not supported in mariadb JDBC connector, can anyone please send me the alternate way to do this process.
MariaDB connector version : mariadb-java-client-1.5.8.jar,
MariaDB version : mariadb-10.1.20-winx64
Following are the code snippet:
Java Code Snippet
Following Exception thrown:
Exception Trace
You could use the Statement.executeUpdate() instead.
Of cause you will need to change your SELECT statement to an UPDATE statement, too.
The disadvantage is that you loose access to the single row data, because you do not select it at all. If you need this, e.g. to calculate the updated value (in your case test#<localipaddress>) you may have to first fire the select as you did, calculate your updates in memory and then use PreparedStatement or Batch Update to execute the according UPDATE statements.
Prepared Statement example:
public static int preparedUpdate(Connection conn, String localIPAddress) throws SQLException {
int numChangedRows = 0;
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
while (rs.next()) {
// id => something unique for this row within the table,
// typically the primary key
String id = rs.getString("id");
String jid = rs.getString("column1");
if("abc".equals(jid)) { // just some nonsense condition
try (PreparedStatement batchUpdate = conn.prepareStatement("UPDATE table1 SET column1 = ? where id = ?")) {
batchUpdate.setString(1, localIPAddress);
batchUpdate.setString(2, id);
numChangedRows = batchUpdate.executeUpdate();
}
}
}
}
return numChangedRows;
}
Batch Update example:
public static int[] batchUpdate(Connection conn, String localIPAddress) throws SQLException {
int[] changedRows = null;
try (PreparedStatement batchUpdate = conn.prepareStatement("UPDATE table1 SET column1 = ? where id = ?")) {
try (Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM table1");
while (rs.next()) {
// id => something unique for this row within the table,
// typically the primary key
String id = rs.getString("id");
String jid = rs.getString("column1");
if("abc".equals(jid)) { // just some nonsense condition
batchUpdate.setString(1, localIPAddress);
batchUpdate.setString(2, id);
batchUpdate.addBatch();
}
}
}
changedRows = batchUpdate.executeBatch();
}
return changedRows;
}
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 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();
}
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
}