Java mysql execute update - java

So I have a method that looks up a foreign key in a database. If the foreign key does not exist it will add an entry into the database. Now what I am doing from that point after inserting the new record, is re-querying again to get the foreign key. Is this overkill or is this the right way to do this? Thanks
private String getTestType(TestResult testResult) {
String testTypeId = "";
String query = String.format("SELECT id FROM test_types WHERE " +
"name='%s'", testResult.getTestType());
try {
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
} else {
st = con.prepareStatement("INSERT INTO test_types (name, " +
"created_at) VALUES (?, ?)");
st.setString(1, testResult.getTestType());
st.setTimestamp(2, new java.sql.Timestamp(System
.currentTimeMillis()));
st.executeUpdate();
st = con.prepareStatement(query);
rs = st.executeQuery();
if (rs.next()) {
testTypeId = rs.getString("id");
}
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("There was an issue getting and or creating " +
"test Type");
}
return testTypeId;
}

Since you are inserting a new row into DB, you have to do a query to get back the auto increment field(id). Currently they way you are doing is workable. But there are few alternatives in query:
Obtaining the id using last_insert_id():
rs = st.executeQuery("select last_insert_id() as last_id");
id= rs.getString("last_id");
Another approach can be doing the MAX over the id column of the table.
I believe these are will be much faster than your query as you are doing string comparison in where clause.

Related

Should not Add the Existing Empno into the database using java and mysql

i am creating a simple employee payroll system leave part. I am ran into the problem with when i add the leave information for employee. all leave information will add all the employees who works on the company. when the new employee comes if i add the leave information for the new employee the leave information again add into the existing employee also.i need to add only new employee only leave information how to do the task.existing record not added again.
employee table
leave table
this is code which i tried for but no error but not working.
String cas = txtcas.getValue().toString();
String anu = txtanu.getValue().toString();
String med = txtmed.getValue().toString();
String year = txtyear.getText();
try {
int c;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/spay","root","");
PreparedStatement pst1 = con.prepareStatement("select empno from registation");
ResultSet rs = pst1.executeQuery();
String empNoValue1 = rs.getString("empno");
PreparedStatement pst2 = con.prepareStatement("select empno from leaves");
String empNoValue = rs.getString("empno");
ResultSet rs1 = pst2.executeQuery();
while (rs.next()) {
if(rs1.next())
{
if(empNoValue1.equals(empNoValue))
{
}
}
else
{
pst = con.prepareStatement("insert into leaves(empno,casual,annual,medical,year)values(?,?,?,?,?)");
pst.setString(1,empNoValue); // employee no how to give
pst.setString(2, cas);
pst.setString(3, anu);
pst.setString(4, med);
pst.setString(5, year);
pst.executeUpdate();
}
}
JOptionPane.showMessageDialog(null,"Leave Insertedddddd");
If I understood it right you want to increase the ID values of some workers.
Connection con = null;
Statement stmt = null;
int id = 0;
try {
Class.forName("org.postgresql.Driver");
con = DriverManager.getConnection("url", "username", "pwd");
con.setAutoCommit(true);
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id FROM userlist ORDER BY id DESC LIMIT 1");
while (rs.next()) {
id = rs.getInt("id");
}
id++;
stmt.execute("INSERT INTO userlist (id) VALUES (" + String.valueOf(id) + ");");
} catch (Exception e) {
e.printStackTrace();
}
I used postgresql so you have to change the queries a bit. The principle is getting the worker with the highest ID, increment the ID by one and rewrite the new ID with maybe other data.
I hope I could help you

Java - Sql query with Alias

I want to retrieve a particular column from the database. For a simple Select statement, I can able to able to retrieve a column like below
public String getDbColumnValue(String tableName, String columnName, String applicationNumber) {
String columnValue = null;
try {
PreparedStatement ps = null;
String query = "SELECT " + columnName + " FROM " + tableName +
" WHERE ApplicationNumber = ?;";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString(columnName);
return columnValue;
}
}
catch (Exception ex) {
}
return columnValue;
}
But, I'm using alias in my query like below. And this query works fine. How to use this in Java to retrieve a particular column
select S.StatusDesc from application A, StatusMaster S
where A.StatusMasterId = S.StatusMasterId and A.ApplicationNumber = '100041702404'
Any help would be greatly appreciated!
I think you are confusing simple aliases, which are used for table names, with the aliases used for column names. To solve your problem, you can just alias each column you want to select with a unique name, i.e. use this query:
select S.StatusDesc as sc
from application A
inner join StatusMaster S
on A.StatusMasterId = S.StatusMasterId and
A.ApplicationNumber = '100041702404'
Then use the following code and look for your aliased column sc in the result set.
PreparedStatement ps = null;
String query = "select S.StatusDesc as sc ";
query += "from application A ";
query += "inner join StatusMaster S ";
query += "on A.StatusMasterId = S.StatusMasterId ";
query += "and A.ApplicationNumber = ?";
ps = conn.prepareStatement(query);
ps.setString(1, applicationNumber);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
columnValue = rs.getString("sc");
return columnValue;
}
Note: I refactored your query to use an explicit inner join instead of joining using the where clause. This is usually considered the better way to write a query.

Return values from DB with another result set

How can I execute this statement and process it java. Is it possible to get a return value and then the next resultset which is the select to employee in the way I'm doing it?
I cannot find the accurate way on Google to perform what I want because all of the examples are results with single SELECTs and cannot find a query with RETURN from DB. But according to this question, it is possible to manage multiple result sets from DB (java) as .NET can do.
I'm using postgresql 9.4 and I don't want to use a stored proc (function) to do what I'm trying to do.
This is the code that I've been trying to test, but I get an exception that there is a syntax error in 'IF' line 1
public Employee getEmployee(Connection con, String code) {
Employee employee = new Employee();
try {
String query =
"IF EXISTS(SELECT * FROM employee WHERE code = ?) THEN "
+ "RETURN 1; "
+ "ELSE "
+ "RETURN 2; "
+ "END IF; "
+ "SELECT EmployeeID, FirstName FROM employee where code = ?; ";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, code);
stmt.setString(2, code);
boolean hasResults = stmt.execute();
int returnValue = 0;
while(hasResults){
ResultSet rs = stmt.getResultSet();
returnValue = rs.getInt(1);
if(returnValue == 1){
hasResults = stmt.getMoreResults();
while(hasResults){
employee.setId(rs.getInt("EmployeeID"));
employee.setFirstName(rs.getString("FirstName"));
}
}
}
return employee;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
You are overcomplicating things (apart from the fact that there is no if in SQL).
Just run the select, if there is no such employee you'll get an empty result set:
public Employee getEmployee(Connection con, String code) {
Employee employee = new Employee();
try {
String query = "SELECT EmployeeID, FirstName FROM employee where code = ?";
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, code);
ResultSet rs = stmt.executeQuery();
if (rs.next()){
employee.setId(rs.getInt("EmployeeID"));
employee.setFirstName(rs.getString("FirstName"));
}
return employee;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
You also might want to move the creation of the Employee instance inside the if (rs.next()) so that if no employee exists your method returns null. The above code would always return an Employee even if there is none
You also should remove the ; from the query string. Although the Postgres driver will happily run statements terminated with ; this is not JDBC compliant and other drivers (or DBMS) might refuse to run it.

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.

Sorted Result Set from DB not apprearring in order while printed in Java

Finally narrowed down the problem, here is what my problem is when i execute a SQL which has 'order by' on that and try to print the result set in Java the result set is not sorted.
But when i execute the SQL separately with my SQL developer, I am seeing the ordered result why is that? Is there any option to solve this?
Below mentioned is method I am using
List getDBValues(short orderBy) throws Exception {
Connection conn = null;
ResultSet rs = null;
List results = nmull;
String sqlStmt = new String();
PreparedStatement ps = null;
try {
conn = Utilities.getConnection(DB);
sqlStmt ="SELECT
COLUMN1,
COLUMN2,
COLUMN3,
FROM SAMPLE_TABLE
WHERE
COLUMN1 IN ('10','15') AND
COLUMN3 IN ('1','2') ORDER BY ? ";
try {
short orderByObj = 0;
if(orderBy < 1){
orderByObj = Short.parseShort(Math.abs(orderBy)+"");
sqlStmt += "DESC";
}else{
orderByObj = orderBy;
}
System.out.println("==================== SQL ==================== \n"+sqlStmt);
ps = conn.prepareStatement(sqlStmt);
ps.setLong(1, orderByObj);
rs = ps.executeQuery();
while (rs.next())
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
catch(SQLException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace()
}
return results;
}
You cannot use a bind variable within the order by statement.
You'll have to append it to the query.
sqlStmt ="SELECT
COLUMN1,
COLUMN2,
COLUMN3,
FROM SAMPLE_TABLE
WHERE
COLUMN1 IN ('10','15') AND
COLUMN3 IN ('1','2') ORDER BY ";
try {
short orderByObj = 0;
if(orderBy < 1){
orderByObj = Short.parseShort(Math.abs(orderBy)+"");
sqlStmt = sqlStmt + " " + orderByObj + " DESC";
}else{
sqlStmt = sqlStmt + " " + orderBy ;
}
System.out.println("==================== SQL ==================== \n"+sqlStmt);
ps = conn.prepareStatement(sqlStmt);
rs = ps.executeQuery();
while (rs.next())
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
There might be problem with you JSP iterations.
Write out the codes you used here. Both i java, jsp.
Use LinkedList kind of collection stuff that stores data with respect to insertion order.
At the risk of being obvious, could it have anything to do with the fact that your SQL query doesn't actually sort the data? Maybe you mean to rewrite with a proper ORDER statement, such as, for example:
SELECT column1, column2 FROM table ORDER BY column1 DESC

Categories