How to check if a Merge query was succesfull in JAVA (ResultSet)? - java

I want to check if this query returns a result or an error.
I use the next() method, for SELECT querys synce it checks if there's a next row but not sure about MERGE
public ResultSet example{
String sqlQuery = "MERGE INTO bonuses b "
+"USING ( "
+"SELECT employee_id, salary, dept_no "
+"FROM employee#link_to) e "
+"ON (b.employee_id = e.employee_id) "
+"WHEN MATCHED THEN "
+"UPDATE SET b.bonus = e.salary * 0.1 "
+"WHEN NOT MATCHED THEN "
+"INSERT (b.employee_id, b.bonus) "
+"VALUES (e.employee_id, e.salary * 0.05) "
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs;
try {
rs = stmt.executeQuery();
Err.errN(rs);
} finally {
}
return rs;
}

you can try this:
........
int affected_rows_number=stmt.executeUpdate("your_query");
affected_rows_number show you how many rows affected. You can understand it worked or now.

Related

Java Sqlite how to print a.rowname

I asked myself how I print a.rowname in Java with jbdc sqlite.
Or did I take the wrong solution to fetch all the Selected data?
I tried this:
String vergleichVon ="DB_18_12_2021_02h13m05s";
String vergleichBis ="DB_18_12_2021_08h28m19s";
Connection connection = null;
try
{
//Connect to Database
connection = DriverManager.getConnection("jdbc:sqlite:"+dataBasePath+"");
Statement c = connection.createStatement();
c.setQueryTimeout(30); // set timeout to 30 sec.
ResultSet rs = c.executeQuery("SELECT a.name, a.pt, b.pt, a.sz, a.bd"+
"FROM "+vergleichVon+" AS a, "+vergleichBis+" AS b "+
"WHERE a.name= b.name AND a.pt>'1000' AND b.pt>='1000' AND a.pt!='n/v' AND b.pt!='n/v' "+
"ORDER BY a.pt DESC");
while(rs.next())
{
// read the result set
System.out.print("nameA = " + rs.getString("a.name"));
System.out.print(" ");
System.out.println("ptB = " + rs.getString("b.pt"));
}
}
And I get this error:
no such column: 'a.name'
In Python it works kind of like this. I can later just get the Selected data from the array:
c.execute('''SELECT a.name, a.pt, b.pt, a.sz, a.bd
FROM '''+vergleich_von+''' AS a, '''+vergleich_bis+''' AS b
WHERE a.name= b.name AND a.pt>'1000' AND b.pt>='1000' AND a.pt!='n/v' AND b.pt!='n/v'
ORDER BY a.pt DESC''')
array = c.fetchall()
You do not select a.spieler
try:
ResultSet rs = c.executeQuery("SELECT a.name as spieler, a.pt, b.pt as bpt, a.sz, a.bd"+
"FROM "+vergleichVon+" AS a, "+vergleichBis+" AS b "+
"WHERE a.name= b.name AND a.pt>'1000' AND b.pt>='1000' AND a.pt!='n/v' AND b.pt!='n/v' "+
"ORDER BY a.pt DESC");
while(rs.next())
{
// read the result set
System.out.print("nameA = " + rs.getString("spieler"));
System.out.print(" ");
System.out.println("ptB = " + rs.getString("bpt"));
}
Update after question edit
Use aliases for the columns without dots:
ResultSet rs = c.executeQuery("SELECT a.name as name, a.pt as apt, b.pt as bpt, a.sz as asz, a.bd as adb"+
"FROM "+vergleichVon+" AS a, "+vergleichBis+" AS b "+
"WHERE a.name= b.name AND a.pt>'1000' AND b.pt>='1000' AND a.pt!='n/v' AND b.pt!='n/v' "+
"ORDER BY a.pt DESC");
while(rs.next())
{
// read the result set
System.out.print("nameA = " + rs.getString("name"));
System.out.print(" ");
System.out.println("ptB = " + rs.getString("bpt"));
}

Resultset.next returns true but doesn't return the value

I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);

How to set list in prepared statement

How can i set list in prepared statement(statement.setString(1, productCode); ).
See below my code snippet.
Thanks
public static List<Message> listAllWonBids(List<Message> productCode,
Connection connection) {
List<Message> winners = new ArrayList<Message>();
String sql = "SELECT b.`id`, b.`msisdn` as msisdn ,b.`productname` as productname, b.`productcode` as productcode, max(b.`amount`) as amount FROM "
+ TableNames.SAVEDBIDSTABLE
+ " b where productcode = ? "
+ " group by amount order by productcode, amount desc limit 1";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
LOGGER.info(sql);
if (connection == null || connection.isClosed())
connection = DBConnection.getConnection();
statement = connection.prepareStatement(sql);
**statement.setString(1, productCode);**
resultSet = statement.executeQuery();
NOTE: productCode is coming from another list shown below
public static List<Message> allProductCode(Connection connection) {
List<Message> productcodes = new ArrayList<Message>();
PreparedStatement statement = null;
ResultSet resultSet = null;
String sql = "SELECT `productCode` FROM " + TableNames.AUCTIONTABLE1
+ " WHERE date(`endDate`) = curdate() order by `id` desc";
That is not possible, either you generate a where clause programmatically using the IN
"where productcode in (" + listToStringEncoding + ")"
or you loop over the list and call the statement multiple times.
Other possibility is to join the 2 statements...
You could combine those two queries. Something like:
String sql = "SELECT b.`id`, b.`msisdn` as msisdn ,b.`productname` as productname, b.`productcode` as productcode, max(b.`amount`) as amount FROM "
+ TableNames.SAVEDBIDSTABLE + " b where productcode in (SELECT `productCode` FROM "
+ TableNames.AUCTIONTABLE1 + " WHERE date(`endDate`) = curdate() order by `id` desc) group by amount order by productcode, amount desc limit 1";
Then you wouldn't need any parameters

LIKE Statements Not Working in Java SQL Prepared Statement

I'm working on creating a Java interface for an SQL database. I'm using prepared statements to perform the search queries, however they only work with "=" statements and not with LIKE statements.
The first sample code using "=" works successfully. The second sample, using a LIKE statement, does not work and just returns empty.
WORKS:
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName = ? ORDER BY aLastName asc");
SearchQuery.setObject(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
DOESN'T WORK:
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName LIKE ? ORDER BY aLastName asc");
SearchQuery.setObject(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
Any help is much appreciated, also if you could explain it to me keeping in mind I'm very new to Java and don't have a lot of programming experience yet.
The rest of my search button's code:
private void button_SearchActionPerformed(java.awt.event.ActionEvent evt) {
String FirstName = textField_FirstName.getText();
String LastName = textField_LastName.getText();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:Alumni_DB");
Statement st=con.createStatement();
con.commit();
System.out.print(FirstName + " ");
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName LIKE ? ORDER BY aLastName asc");
SearchQuery.setString(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
String aUID="",aFName="",aLName="",aMInitial="",aHomePhone="",aCellPhone="";
while(rs.next())
{
aUID=rs.getString(1);
aFName=rs.getString(2);
aLName=rs.getString(3);
aMInitial=rs.getString(4);
aHomePhone=rs.getString(5);
aCellPhone=rs.getString(6);
System.out.println("UID " + aUID + " First Name " + aFName + " Last Name " + aLName + " Middle Initial " + aMInitial + " Home Phone " + aHomePhone
+ " Cell Phone " + aCellPhone);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
Note: Anything with the prefix 'a' is referring to a database column

select same value from N rows in a mysql database

I m new to mysql and m trying to select N rows from a mysql table in eclipse. Now, i want to select N rows of same value from the database. I am using the following code
User user= null;
ArrayList<User> searchedUsers = new ArrayList<User>();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String authenticationSql;
authenticationSql = "SELECT * FROM users WHERE " + searchIn + " = ?";
log.info(authenticationSql);
stmt = (PreparedStatement) dbConn.prepareStatement(authenticationSql);
stmt.setString(1, searchFor);
rs = stmt.executeQuery();
while (rs.next()) {
user = new User(rs.getString("username"),
rs.getInt("user_type"), OnlineStatus.ONLINE);
searchedUsers.add(user);
}
rs.close();
stmt.close();
} catch (SQLException ex) {
log.error("SQLException: " + ex.getMessage());
log.error("SQLState: " + ex.getSQLState());
log.error("VendorError: " + ex.getErrorCode());
}
The problem is this code only returns me the first value of the search and not the rest of the values are selected from the database. Can please some one point out what i m doing wrong here. Any help will be appreciated. Thanks.
You cannot use count(*) in statement like this.
It should give you some error like Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
I think it's the COUNT(*) from your SELECT that is grouping your results. Try without it

Categories