ResultSet getDate(1) - sql

How to return oracle.sql.DATE from ResultSet?
It returns a Java date, not the ORACLE date.
I get an error:
Type mismatch: cannot convert from Date to DATE
ResultSetIterator iter;
...
ResultSet rs = iter.getResultSet();
if (rs.next()) {
date = rs.getDate(1);
}
My query:
SELECT MIN(date_created) FROM tbl_user group by date_created;

What is oracle.sql.DATE? Do you mean java.sql.Date?
What do you mean by java Date? Do you know that java.sql.Date is subclass of java.util.Date?
try this what will be the output?
ResultSet rs = iter.getResultSet();
if (rs.next()) {
date = rs.getDate(1);
if (date instanceof java.sql.Date)
System.out.println("sql date");
if (date instanceof java.util.Date)
System.out.println("util date");
}
edit:
I see here you can probably do something like this:
ResultSet rs = iter.getResultSet();
if (rs.next()) {
date = rs.getDate(1);
if (date instanceof java.sql.Date)
return new oracle.sql.DATE(date);
}

You can cast the ResultSet to an OracleResultSet and then use the getDATE() method:
OracleResultSet rs = (OracleResultSet)iter.getResultSet();
if (rs.next()) {
oracle.sql.DATE date = rs.getDATE(1);
}

Related

Deleting the last row in a table. SQL/Netbeans

In java, i am trying to delete the last row of my database. The database has 15 rows and i want to the delete the 15th one. The columns are called Initials and Score.
Intials Scores
rows# 1. ADS 2343
2. DDE 5454
15. TBK 332
I can't have it selecting TBK because i'm wanting it to delete the 15th one no matter what it is so a new one can be added. Everywhere I've looked it's always has to be specific or a delete all rows. Can anyone help? Many thanks to those who help. :)
Assuming id is an identity column
DELETE FROM table
WHERE id = (SELECT MAX(id) FROM table)
OP : I am trying to delete the last row of my database.
make resultset updatable : ResultSet.CONCUR_UPDATABLE);
set cursor to last record : resultSet.last();
delete last Record : resultSet.deleteRow();
for further use of rs you should set : resultSet.beforeFirst();
private static int delLastRow(ResultSet resultSet) {
if (resultSet == null) {
return 0;
}
try {
resultSet.last();
int delID = resultSet.getInt(1);
resultSet.deleteRow();
System.out.println("Deleted id :" + delID);
resultSet.beforeFirst();
return delID;
} catch (SQLException exp) {
exp.printStackTrace();
} finally {
try {
resultSet.beforeFirst();
} catch (SQLException exp) {
exp.printStackTrace();
}
}
return 0;
}
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//rs will be scrollable, will not show changes made by others,
//and will be updatable
String sql;
sql = "SELECT * FROM `order details`";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("Deleted id :"+ delLastRow(rs));
....
}

Oracle columns update not happpening

I am trying to update a few columns in a Oracle table from my C# code.
Here is my method:
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
whereClause = String.Format(whereClause, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), whereClause);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
cmd.ExecuteNonQuery();
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
Here is the Query:
UPDATE
{0}
SET
SYNC_STATUS = '{1}'
,SYNC_DATE = TO_DATE('{2}', 'yyyy/mm/dd')
{3}
And the where clause will look something like:
WHERE ID = {0}
This method updates about 10 records, and the rest stays null. This mehod does return true, and I have debugged, no exception is thrown.
Why does it not update all records?
This isn't an answer but might help debug the problem.
Instead of the like:
cmd.ExecuteNonQuery();
put in this:
int count = cmd.ExecuteNonQuery();
if (count == 0)
{
Console.WriteLine("");
}
Put a break on the Console.WriteLine("") and run it. The debugger will stop if no rows were updated. You can then check the query, and whether or not that ID actually exists.
The problem was with the WHERE clause. Since it contains a place holder {0}, after I I formatted the WHERE clause, the ID always stayed to the value it was formatted with first.
This is what my new method looks like.
private static bool UpdateOracleTable(OracleTable table, string whereClause, List<int> entIDs)
{
try
{
var tableName = table.ToString();
using (OracleConnection conn = new OracleConnection(_oracleConnection))
{
conn.Open();
foreach (var id in entIDs)
{
string originalWhere = whereClause;
originalWhere = String.Format(originalWhere, id);
var query = Resources.UpdateOracle;
query = String.Format(query, tableName, "20", DateTime.Now.ToString("yyyy/MM/dd"), originalWhere);
using (OracleCommand cmd = new OracleCommand(query, conn))
{
bool success = cmd.ExecuteNonQuery() > 0;
}
}
}
return true;
}
catch (Exception ex)
{
Log.Debug(LogType.Error, ex);
return false;
}
}
As can be seen, I added a variable 'originalWhere', that gets formatted, but most importantly, is being set to original WHERE clause parameter passed, so that it will always contain the place holder.

How to query database and return single row only

I'm new to programming and I'm trying to do simple projects to learn more. I've done researching, but I can't seem to find a solution to my problem. Perhaps, my program is not properly structured, but here it goes:
THIS BLOCK WILL VALIDATE IF THE ENTERED EMPLOYEE ID ALREADY EXISTS IN DATABASE. THIS IS CALLED IN A SERVLET
public boolean login(String employeeID) throws SQLException {
String sql = "select count(*) as count from employees where emp_id=?";
statement = connection.prepareStatement(sql);
statement.setString(1, employeeID);
rs = statement.executeQuery();
if (rs.next()) {
count = rs.getInt("count");
}
rs.close();
if (count == 0) {
return false;
} else {
return true;
}
}
/* METHOD BELOW ITERATES THE FIELDS FROM MYSQL DATABASE, BUT IT DISPLAYS ALL OF IT.
I JUST WANT TO GET A SINGLE ROW MATCHING THE EMPLOYEE ID PARAMETER ENTERED.*/
public List<EmployeeNumber> _list() throws SQLException {
List<EmployeeNumber> result = new ArrayList<>();
String sql = "select * from employees";
statement = connection.prepareStatement(sql);
rs = statement.executeQuery();
if (rs.next()) {
EmployeeNumber emp = new EmployeeNumber();
emp.setEmployeeNumber(rs.getString(1));
emp.setFirstName(rs.getString(2));
emp.setLastName(rs.getString(3));
emp.setEmail(rs.getString(4));
emp.setDepartment(rs.getString(5));
emp.setFirstApprover(rs.getString(6));
emp.setSecondApprover(rs.getString(7));
result.add(emp);
}
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
return result;
}
}
I think it has something to do with my SQL Query statement but I can't figure out how to fix it.
So in a nutshell, when I submit the employee ID from JSP page, it will validate if that exists, and if it does, I want to display all the column fields within the same row where this employee ID is positioned. How do I do that? Results will be displayed on another JSP page.
Thank you.
You're first counting how many employees have the given ID. Then you're selecting all the rows from the employee table.
Skip the first query, and only use the second one, but by adding a where clause, just as you did with the first query:
select * from employees where emp_id=?
Then after you've bound the parameter (as you did for the first query), test if there is a row returned:
if (rs.next()) {
// get the data, and return an EmployeeNumber instance containing the data
}
else {
// no employee with the given ID exists: return null
}
Note that the method shouldn't return a List<EmployeeNumber>, but an EmployeeNumber, since you only want to get 1 employee from the table.
Maybe try something like this?
String sql = "select count(*) as count from employees where emp_id=?";
statement = connection.prepareStatement(sql);
statement.setString(1, employeeID);
int count = statement.ExecuteScalar();
if (count == 0) {
return false;
} else {
return true;
}
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx
You can also set a breakpoint and step through your code and see where the exception is being thrown. That would help us, knowing the exception message and where it's breaking.

Using SQL Server Date datatype and C# DateTime to select records

I have an ActionResult where I want to select records based on a date column in SQL Server. This date is in a column of type Date. I can't directly compare the dates since C# DateTime includes the time component and the Date datatype does not. Is there a nice way to do this?
public ActionResult AbsencesByDate(DateTime date)
{
var absences = from attendance in db.Attendances
where attendance.Date == date
select new
{
returnedPersonID = attendance.PersonID,
FullName = attendance.Person.FName + " " + attendance.Person.LName,
};
return Json(absences, JsonRequestBehavior.AllowGet);
}
You could remove the time part from your date parameter in your function.
Something like this :
public ActionResult AbsencesByDate(DateTime date)
{
date = date.Date;
var absences = from attendance in db.Attendances
where attendance.Date == date
select new
{
returnedPersonID = attendance.PersonID,
FullName = attendance.Person.FName + " " + attendance.Person.LName,
};
return Json(absences, JsonRequestBehavior.AllowGet);
}
try using:
where attendance.Date == date.Date

Querying SQLite in android( Summation of column values)

Hi guys I want to get the summation of column values from my sqlite database in android.
and am trying to use this to get me the sum of column KEY_COST.
public Cursor fetchAllCost() {
return mDb.query(
DATABASE_TABLE,
new String[] { "SUM(KEY_COST)"},
null,
null,
null,
null,
null);
}
but its giving me a cursor and I do not know how to get the value from the Cursor object. Any one help!!!
You can return scalar values like so:
public int getColumnData() {
mDb = mDbManager.getReadableDatabase();
final SQLiteStatement stmt = mDb
.compileStatement("SELECT SUM(KEY_COST) FROM...");
// Cast as appropriate
return (int) stmt.simpleQueryForLong();
}
Or alternatively, depending on the data type use simpleQueryForString().
You should just move to the first result in the cursor with cursor.moveFirst() and then you can do cursor.getInt(1) to get the scalar value.
rawQuery
Sum value is on first column - cursor.getInt(0);
Cursor cursor = database.rawQuery(
"SELECT SUM(" + COL_NAME + ") FROM " + TABLE_NAME, null);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}
query
String[] columns = new String[] {
"sum(" + DbHelper.C_COUNT_OF_WORDS + ")"
};
String where = null;
String whereArgs[] = null;
String groupBy = null;
String having = null;
String order = null;
String limit = null;
database = dbHelper.getReadableDatabase();
Cursor cursor = database.query(DbHelper.TABLE_STATISTICS, columns, where, whereArgs, groupBy, having, order, limit);
if(cursor.moveToFirst()) {
return cursor.getInt(0);
}