I do simple alarm and i need show alert if value from column 0 == today.
Calendar cal = new GregorianCalendar();
int day = cal.get(Calendar.DAY_OF_MONTH);
try {
File currDir= new File ("Baza.db");
String sc = currDir.getAbsolutePath();
sc = sc.substring(0, sc.length());
String url = "jdbc:sqlite://"+sc;
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Day FROM Month");
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
if(jTable1.getValueAt(0, 0).equals(day)){
JOptionPane.showMessageDialog(null, "Do your question!");
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
}
I trying use method getColumn, getColumnModel and getSelectedColumn but but nothing compared my calculations..
Your day variable is of type int and jTable1.getValueAt(0, 0) returns an Object hence both are of different type and will always return false upon comparison.
As you want to compare the equality of them as string, hence you should change your comparison from this,
if(jTable1.getValueAt(0, 0).equals(day)){
to,
if(String.valueOf(jTable1.getValueAt(0, 0)).equals(String.valueOf(day))){
Or, you may parse the value in Jtable column to int and then compare the integer value like this,
if(Integer.parseInt(jTable1.getValueAt(0, 0).toString()) == day){
However, I'll prefer the first way to compare as string, as second way can run into NumberFormatException
Related
I'm getting this error and I don't why I tried the statement on workbench and it worked.
I'm looking also to improve my dates subtracting code basically I'm getting deadline from the table and I'm subtracting from today's date.
public boolean checkLessThanWeek(User userWhoWantsToExtendDeadline,BorrowedBook book) throws ParseException {
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT Deadline FROM library_students.borrowedcopies WHERE LenderToID =" + "'" + userWhoWantsToExtendDeadline.getId()+ "'"+"And Barcode="+"."+book.getbookID());
if (rs.next()) {
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date deadline = format.parse(rs.getString(1));
Date date=new Date();
String today=format.format(date.getDate());
date = format.parse(today);
long milliseconds=date.getTime()-deadline.getTime();
long days = milliseconds / (1000 * 60 * 60 * 24);
System.out.print(days);
}
rs.close();
return true;
} catch (SQLException ex) {
ex.printStackTrace();
return false;
}
}
It is most likely because book.getbookID() returns null and because you for some reason have a dot (.) before it in your Sql. Besides this it is preferred to have a parameterized Sql statement using ? and also basic error handling is a good thing.
if (userWhoWantsToExtendDeadline == null || book == null || book.getbookID() == null {
//throw exception perhaps or log?
return false;
}
String query = "SELECT Deadline FROM library_students.borrowedcopies WHERE LenderToID = ? AND Barcode = ?";
Statement stmt = con.createStatement(query);
stmt.setInt(1, userWhoWantsToExtendDeadline.getId());
stmt.setString(2, book.getbookID());
ResultSet rs = stmt.executeQuery();
Note that I assumed your first parameter is an int and the second one is a String but of course ths might need to be changed
I want compare to the data sent with all data in the db. this coce compare the date insert only with the last row. how can I compare with all row in the db?
................................................................................................
String sData= request.getParameter("idatadata");
String sAzienda= request.getParameter("idazienda");
String sCommessa= request.getParameter("idcommessa");
String date = "";
String company = "";
String order = "";
Connect con = new Connect();
try {
Connection connection = con.createConnection();
Statement statement = connection.createStatement();
String sql ="SELECT * FROM table";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()) {
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
}
if((sData.equals(date) && sAzienda.equals(company)) && sCommessa.equals(order)) {
out.print("already sent");
con.closeConnection(connection);
}
else {
DbConnect.insertInDb(connection, sData, sOre, sMinuti, sAzienda, sCommessa, sRifInterno);
dbc.closeConnection(connection);
response.getWriter().append("ok! ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
The reason why you are checking only the last row, is that your while loop keeps overwriting your local variables each time you retrieve a row:
while(resultSet.next()) {
// these lines overwrite the local vars for each row
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
}
But you don't actually check the local vars inside the loop before moving on to the next row from the db. You should add the check into the loop:
while(resultSet.next()) {
date = resultSet.getString("iddata");
company = resultSet.getString("idazienda");
order = resultSet.getString("idcommessa");
// add your check here
if((sData.equals(date) && sAzienda.equals(company)) && sCommessa.equals(order)) {
out.print("already sent");
break;
}
}
Preferably, just perform a select based on the data you are looking for. If you get no results, then the data isn't in the db. This method is much more efficient. If you do decide to go down this path (which is a good idea), use a prepared statement so that you don't introduce a SQL injection vulnerability into your code.
I'm trying to create a method to recognize MySQL datatypes to create queries, but it doesn't work for some reason.
Here is the code that fails:
int type = meta.returnDataType(data[i], table);
if(type == 4){
preparedStatement.setString(i + 1, data[i]);
System.out.println("String går");
}if(type == 12){
preparedStatement.setInt(i + 1, Integer.parseInt(data[i]));
System.out.println("int går");
}else if(type == 92){
DateFormat formatter = new SimpleDateFormat("HH:mm");
preparedStatement.setTime(i + 1, new java.sql.Time(formatter.parse(data[i]).getTime()));
}else if(type == 93){
DateFormat formatter = new SimpleDateFormat("yyyy:MM:dd HH:mm");
preparedStatement.setTimestamp(i + 1, new java.sql.Timestamp(formatter.parse(data[i]).getTime()));
}
and here's my returnDataType method:
try(Connection con = DBConnection.getMySQLDataSourceForUpdate().getConnection();
Statement stmt = con.createStatement()){
String query = "select * from " + table;
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
return rsmd.getColumnType(1);
}catch(IOException e){
}catch (SQLException e){
}
Now the problem is that it doesn't recognize varchar, even though the number 12 is returned every time I try it with system out print. When I try to detect it with if statements or switch, the result is either that they only register integers or they treat everything as integers. I can't seem to see why this is the case.
My CSV file goes like this, the first is an int and the second is a String. At least that's what it should be and that's the way it is in the database.
1,Per Lauvås
2,Per Per
Your returnDataType method always returns the type of the first column of a table. You need to fix that. You should use the parameter metadata of the prepared statement, or maybe the column metadata from DatabaseMetaData. Or at least access the right column index.
You also have switched your if-branches. Type 4 is java.sql.Types.INTEGER, but you attempt to set it as a string, while type 12 is java.sql.Types.VARCHAR, but you try to set it as an integer (with a conversion that might fail).
Sidenote: You should not use integer values like 4, 12, 92 and 93, instead you should use the java.sql.Types constants INTEGER, VARCHAR, TIME and TIMESTAMP. It will make your code more readable and make it easier to detect mistakes like the above.
This post is related to my previous post.
Recently i have a project in which i should send an string and two datetime field to SQL Server 2014 and get some fields.(Locaitions)
So i created two DatePicker, that End User can select the date he want.
And instance of a Calender.
Well,with help of my friends here, i used this till now :
Calendar finalCalendar = Calendar.getInstance();
int fDay = datePicker2.getDayOfMonth();
int fMonth = datePicker2.getMonth();
int fYear = datePicker2.getYear();
finalCalendar.set(Calendar.YEAR, fYear);
finalCalendar.set(Calendar.MONTH, fMonth);
finalCalendar.set(Calendar.DAY_OF_MONTH, fDay);
finalCalendar.set(Calendar.HOUR, 0);
finalCalendar.set(Calendar.MINUTE, 0);
finalCalendar.set(Calendar.SECOND, 0);
finalCalendar.set(Calendar.MILLISECOND, 0);
SimpleDateFormat fSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
setFinalDate(fSimpleDateFormat.format(finalCalendar.getTime()));
Well, when i pass it to my SP,it gives me :
java.lang.NumberFormatException: Invalid int: "18 12:00:00.000"
That 18 is the day i have chosen, and 12 as you see is the time i have set to 0,also Minute,Second and mili second.
And i try below code to see if the time the code returns is true or not :
Toast.makeText(getApplicationContext(), getFinalDate(), Toast.LENGTH_SHORT).show();
and it shows correct time that i have chosen from DatePicker.
And when i insert this format of time in SQL Server Management Console it works properly.
And i pass this to SQL Server Stored Procedure from android as below.
callableStatement.setDate(3, java.sql.Date.valueOf(getFinalDate()));
I tried different ways in google.
Different formats of SimpleDateFormat.
I think somewhere i make a mistake.
Any help will appreciate.
And I have a ConnectionHelper Class that works correctly.
I Instance of this.
And call CallableStatement.
CallableStatement callableStatement;
ConnectionHelper connectionHelper1 = new ConnectionHelper();
try {
callableStatement = connectionHelper1.getMyConnection().prepareCall("{call SpSelectTrackVehiclePath(?, ?, ?)}");
callableStatement.setString(1, IMEArrayAdapter.getItem(listView.getCheckedItemPosition()));//IMEArrayAdapter in below will explain,gives the first field of SP.
callableStatement.setTimestamp(2, new java.sql.Timestamp(startCalendar.getTimeInMillis()));
callableStatement.setTimestamp(3, new java.sql.Timestamp(finalCalendar.getTimeInMillis()));
callableStatement.addBatch();
callableStatement.executeBatch();
ResultSet resultSet = callableStatement.executeQuery();
if(resultSet.next()) {
do {
Toast.makeText(getApplicationContext(), "Bingoo", Toast.LENGTH_SHORT).show();
spOut.add(resultSet.getDouble("Latitude"));
i++;
} while (resultSet.next());
}else
{
Toast.makeText(getApplicationContext(), "Error ! ", Toast.LENGTH_SHORT).show();
}
} catch (SQLException e) {
e.printStackTrace();
}
The first Field of this is String that i get from another Table of DB.
Like this(In onCreate Method) :
ConnectionHelper connectionHelper = new ConnectionHelper();
try {
Statement statement = connectionHelper.getMyConnection().createStatement();
ResultSet resultSet = statement.executeQuery("select Id from Device");
while(resultSet.next())
{
String ime;
ime = resultSet.getString("Id");
IMEIs.add(ime); //This is ArrayList<String> Type
IMEArrayAdapter.getItemViewType(R.id.listView); //get the listView id in XML,
listView.setAdapter(IMEArrayAdapter); //with this line it set Adapter and all id shows in my ListView
}
connectionHelper.closeConnection();
} catch (SQLException e) {
e.printStackTrace();
connectionHelper.closeConnection();
}
And In MSSQL Server Management when i execute this SP with fiels Like this :
IMEI : xxxxxxx
firsDate : 2015-11-18 12:00:00:00
lastDate : 2015-11-24 12:00:00:00
It returns the values.
I execute like this is MSSQL Server Management Studio :
USE [xxxxx]
GO
DECLARE #return_value int
EXEC #return_value = [dbo].[xxxxxx]
#DeviceId = N'xxxxxxxxxxxx',
#DateTimeBegin = N'2015-11-18 00:00:00:000',
#DateTimeEnd = N'2015-11-24 00:00:00:000'
SELECT 'Return Value' = #return_value
GO
I copy the execute code of SP in MSSQL Server Management Studio.(above)
I can not see what your getFinalDate() is returning I guess the String yyyy-MM-dd hh:mm:ss, the correct way on java.sql.Date.valueOf should be yyyy-MM-dd, do not include the time
but since you have the Calender object why not do something like this (avoid all parsing)
callableStatement.setDate(3, new java.sql.Date(finalCalendar.getTimeInMillis()));
important is that your column on database is of type DATE
if it is TIMESTAMP or DATETIME you should use:
callableStatement.setTimestamp(3, new java.sql.Timestamp(finalCalendar.getTimeInMillis()));
and yes in this case passing string in valueOf, the string format should be yyyy-MM-dd hh:mm:ss
EDIT: This has nothing to do with original question but a follow up on CallableStatement.
If the callable statement is a query (return resultset), you need to registrer output and you do not addBatch the code would be something like this:
callableStatement = connectionHelper1.getMyConnection().prepareCall("{call SpSelectTrackVehiclePath(?, ?, ?,?)}");
callableStatement.setString(1, IMEArrayAdapter.getItem(listView.getCheckedItemPosition()));//IMEArrayAdapter in below will explain,gives the first field of SP.
callableStatement.setTimestamp(2, new java.sql.Timestamp(startCalendar.getTimeInMillis()));
callableStatement.setTimestamp(3, new java.sql.Timestamp(finalCalendar.getTimeInMillis()));
callableStatement.registerOutParameter(4, java.sql.Types.INTEGER);
ResultSet resultSet = callableStatement.executeQuery();
I have used if loop to compare the values present in table and the value entered from the user, but in the code its not entering to if loop rather it is entering to else loop, i need the suggestion for the problem.
Here is the code :
public void idExists(String SkillID) {
try{
Connection conn = dbconnect();
conn.setReadOnly(false);
Statement st = conn.createStatement();
String skilid= "Select [Skill ID]from [Skill Master$]";
ResultSet rs = st.executeQuery(skilid);
while(rs.next()){
String Skill = rs.getString("Skill ID");
System.out.println(SkillID);
}
if (SkillID==Skill) {
System.out.println("the skill id exist");
}
else {
System.out.println("the skill id doesnt exist");
}
endConnect();
}
catch(SQLException e) {
System.err.println("Got an exception in idexist");
System.err.println(e.getMessage());
}
}
}
You're comparing string value by reference.
Since your variable refer to two different String instances with the same value, the condition is false.
You should compare strings using the equals method.
Also, you probably want to put the if inside the loop.
Finally, you should replace all of that code with a (parameterized!) WHERE clause.