Check if exists row else insert accordingly - java

I'm trying to check if the database has the row Comment matches according from getComments2.
If there exists such row, proceed with the next data checking else it will execute the insert statement
After I ran this code, it gave me:
java.sql.SQLException: Illegal operation on empty result set (When database is empty) or
java.sql.SQLException: After end of result set (When database is filled).
Code:
String url = "test";
String getComments2 = "test1";
String getTime1 = "test2";
String sqlSelect = "Select comment from predata";
PreparedStatement ps1 = conn.prepareStatement(sqlSelect);
ResultSet rs = ps1.executeQuery();
boolean exists = false;
while(!rs.last()||(!exists)) {
rs.next();
if(rs.getString("Comment").compareTo(getComments2)==0) {
exists = true;
}
if(!exists||rs ==null) {
PreparedStatement ps = conn.prepareStatement("INSERT into predata (topic,comment,date) VALUES (?,?,?)");
ps.setString(1, url);
ps.setString(2, getComments2);
ps.setString(3, getTime1);
ps.executeUpdate();
}
}

rs.last() moves the cursor to the last row. Then rs.next() moves it past the last row, so rs.getString("Comment") throws an exception.
The correct logic should be:
boolean exists = false;
while (rs.next() && !exists) {
if(rs.getString("Comment").equals(getComments2)) {
exists = true;
}
}
if (!exists) {
PreparedStatement ps = conn.prepareStatement("INSERT into predata (topic,comment,date) VALUES (?,?,?)");
ps.setString(1, url);
ps.setString(2, getComments2);
ps.setString(3, getTime1);
ps.executeUpdate();
}

You can use Merge in your query itself instead of checking condition in code. Else you can user Insert or Replace in query itself.

Related

Truncated incorrect DOUBLE value using DELETE statement

int d1;
String attribute = comboBox1.getSelectedItem().toString(); // a combo box
System.out.println(attribute);
String data = t.getText(); // a textfield
System.out.println(data);
if (attribute.equals("COURSE_ID")) {
IsNumber in = new IsNumber();
d1 = in.stringToInt(data);
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("connection success!!");
String sql = "DELETE FROM course WHERE ? = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, attribute);
statement.setInt(2, d1);
boolean rows = statement.execute();
if (rows == true) {
new ViewDatabase(user, name, pswrd);
System.out.println("COURSE_ID UNIT UPDATE SUCCESSFUL!");
frame.setVisible(false);
} else if (rows == false) {
JOptionPane.showMessageDialog(null, "Cannot find row!",
"ERROR", JOptionPane.ERROR_MESSAGE);
}
statement.close();
connection.close();
} catch (SQLException e) {
System.out.println("& i oop");
e.printStackTrace();
}
For this piece of code, whenever I try to run it, it returns "Data truncation: Truncated incorrect DOUBLE value: 'COURSE_ID'". I'm not sure what this is referring to and I searched and found some people saying that this error message is misleading, though I only found answers to selects, inserts, and updates, but not deletes.
I also turned off strict mode in MySQL, as advised from the internet, but to no avail.
You can't bind strings to actual column names in a prepared statement. So, the attribute column names must be hard-coded. One pattern which might work would be:
String sql = "";
if ("COL1".equals(attribute)) {
sql = "DELETE FROM course WHERE COL1 = ?";
}
else if ("COL2".equals(attribute)) {
sql = "DELETE FROM course WHERE COL2 = ?";
}
else {
sql = "DELETE FROM course WHERE COL3 = ?";
}
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, d1);
boolean rows = statement.execute();

How to change value of variable when found user with same name in Database?

I want to change value of doesThatUsernameExist to true if in my database, user with same username exist.
I don't know how to make it by SQL code.
That's how I wanted to method looks like:
public boolean doesAccountWithThatUsernameExist(User user) throws SQLException {
boolean doesThatUsernameExist = false;
PreparedStatement preparedStatement = connection.prepareStatement("SELECT username FROM user WHERE username=?"); // < that's wrong
preparedStatement.setString(1, user.getName());
ResultSet result = preparedStatement.executeQuery();
....
return doesThatUsernameExist;
}
resultset.next() returns true if there is a matching record, false otherwise. so you can use its result:
public boolean doesAccountWithThatUsernameExist(User user) throws SQLException {
boolean doesThatUsernameExist = false;
PreparedStatement preparedStatement = connection.prepareStatement("SELECT username FROM user WHERE username=?"); // < that's wrong
preparedStatement.setString(1, user.getName());
ResultSet result = preparedStatement.executeQuery();
doesThatUsernameExist = result.next();
return doesThatUsernameExist;
}

Updating a value in a random row through java in a sql table

Image of my table as it is when I start this program.
What I have is a mostly empty table and I am trying to assign a value to a fixed number of elements. The column I am trying to edit is "Geschlecht" and the number of rows I want to edit is "copyMaen" (~50.000 entries). I would like to only select the rows where the value of "Geschlecht" was NULL before and I would like to select the rows randomly.
I am using SQLite through a JDBC driver.
This is the first time for me working with sql. This is how I tried to do it.
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Geschlecht FROM individuen WHERE Geschlecht IS NULL;");
PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen");
while (copyMaen != 0) {
if (rs.getRowId((int) (Math.random() * ReadCSV.sumBev)) == null) {
ps.setInt(2, 0);
ps.executeUpdate();
copyMaen--;
}
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
Obviosly this throws me Errors and I am not really sure how to go on from there. Could somebody point me in the right direction?
For anybody interested this is the solution:
try {
Statement stmt = DBController.connection.createStatement();
String select = "SELECT ID FROM individuen WHERE Geschlecht is NULL ORDER BY RANDOM()" +
" LIMIT " + Integer.toString(copyMaen);
ResultSet rs = stmt.executeQuery(select);
PreparedStatement ps = DBController.connection.prepareStatement("UPDATE individuen set Geschlecht = ? WHERE ID = ?;");
// rs.beforeFirst();
int count = 0;
while (rs.next()) {
ps.setInt(1, 0);
ps.setInt(2, rs.getInt(1));
ps.addBatch();
if (count%100==0) {
System.out.println(count);
}
count++;
}
DBController.connection.setAutoCommit(false);
ps.executeBatch();
DBController.connection.setAutoCommit(true);
} catch (SQLException e) {
e.printStackTrace();
}
}
Try this,
Below update query is enough for update all row where Geschlecht is
null.
try {
Statement stmt = DBController.connection.createStatement();
String updateTableSQL = "UPDATE individuen set Geschlecht = ? where Geschlecht IS NULL";
PreparedStatement preparedStatement = dbConnection.prepareStatement(updateTableSQL);
preparedStatement.setString(1, "0"); // set zero where Geschlecht null found
// execute update SQL stetement
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}

Why this java code doesn't get last updated ID?

I was getting last inserted ID from below code but as I changed it for update it always returns me 0 as last updated ID. Is there any different way to get last Updated id in java using prepared statements?
public static String updateRegistrationInfo(Integer COMPANY_ID, String FIRST_NAME, String LAST_NAME, String MOBILE_NO,
String WORK_EMAIL, String PASSWORD) throws Exception {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Integer last_inserted_id = 0;
String insertTableSQL =
"UPDATE USER_DETAILS SET COMPANY_ID=?,FIRST_NAME=?, LAST_NAME=?, MOBILE_NO=?, WORK_EMAIL=?, PASSWORD=? WHERE WORK_EMAIL=? AND MOBILE_NO=?";
try {
dbConnection = getConnection();
//--USER_ID IS SET TO AUTO INCREMENT PRIMARY KEY
String returnCols[] = { "USER_ID" };
//--INSERTING MEETING DETAILS
preparedStatement = dbConnection.prepareStatement(insertTableSQL, returnCols);
preparedStatement.setInt(1, COMPANY_ID);
preparedStatement.setString(2, FIRST_NAME);
preparedStatement.setString(3, LAST_NAME);
preparedStatement.setString(4, MOBILE_NO);
preparedStatement.setString(5, WORK_EMAIL);
preparedStatement.setString(6, PASSWORD);
preparedStatement.setString(7, WORK_EMAIL);
preparedStatement.setString(8, MOBILE_NO);
// execute insert SQL stetement
preparedStatement.executeUpdate();
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
last_inserted_id = rs.getInt(1);
}
return last_inserted_id.toString();
} catch (SQLException e) {
return e.getMessage() + " ERROR CODE: " + e.getErrorCode();
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
dbConnection = null;
}
}
}
Unlike INSERT which makes new rows, UPDATE operates on existing rows, and therefore it does not generate new row keys. When you make this call
ResultSet rs = preparedStatement.getGeneratedKeys();
if (rs.next()) {
last_inserted_id = rs.getInt(1);
}
the result comes back empty, so last_inserted_id remains zero.
The logic behind this is simple: in the INSERT you do not know what the key is going to be, so JDBC lets you retrieve it. In the UPDATE you know what key you are setting - it's the COMPANY_ID, - so you do not need a way to retrieve it back.

How to create Java method to count rows in Oracle table

I want to create Java method which can count the rows in Oracle table. So far I made this:
public int CheckDataDB(String DBtablename, String DBArgument) throws SQLException {
System.out.println("SessionHandle CheckUserDB:"+DBArgument);
int count;
String SQLStatement = null;
if (ds == null) {
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException();
}
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQLStatement = "SELECT count(*) FROM ? WHERE USERSTATUS = ?";
ps = conn.prepareStatement(SQLStatement);
ps.setString(1, DBtablename);
ps.setString(2, DBArgument);
ResultSet result = ps.executeQuery();
if (result.next()) {
count = result.getString("Passwd");
}
conn.commit();
committed = true;
} finally {
if (!committed) {
conn.rollback();
}
}
} finally {
/* Release the resources */
ps.close();
conn.close();
}
return count;
}
I want to use for different tables. This is the problem that I cannot solve:
count = result.getString("row");
Can you help me to solve the problem?
count = result.getInt(1);
This is needed, because count is int. And you can specify the index of the row returned by the query, you don't need to access it by name.
But you could also do:
count = result.getInt("count(*)");
This should do it:
count = result.getInt("count(*)");
You need to use the same name as you specified in your query to get the value. You could also make your
count = result.getString("row");
work by changing your query to
SQLStatement = "SELECT count(*) as row FROM ? WHERE USERSTATUS = ?";
You cannot use bind variable in place of a database object in an SQL query, can you? It can only be used for parameter binding.
Try this instead,
"SELECT count(*) as row_count FROM " + DBtablename + " WHERE USERSTATUS = ?";
This could be vulnerable to SQL Injection so you might want to check that DBtablename parameter is a valid database object name (i.e. at most 30 bytes long without spaces, and contains only valid chars for database object identifiers).
count = result.getInt("row_count");

Categories