I am using MySQL 5.5 and I am inserting datetime into my table through Java, using the query:
INSERT INTO player_sale(transaction_id,player_id,game_id,game_type_id,ticket_nbr,mrp_amt,deduct_from_bonus,deduct_from_deposit,deduct_from_winning,good_cause_amt,vat_amt,taxable_sale,transaction_date,is_cancel) VALUES(48160,1001501,1,2,0,1.0,0.0,1.0,0.0,0.0,0.0,1.0,'2015-07-09 18:45:01','N');
but the entry inserted is 0000-00-00 00:00:00 in the transaction_date column.
In addition to it, when I am executing the above query, through the query browser interface of MySQL, the correct datetime is inserted . The datatype of transacion_date is datetime.
I have dug out a lot of web, but I couldn't find the answer regarding the same.
I used the following java code :
try{
Timestamp transactionDate = new Timestamp(Calendar.getInstance().getTimeInMillis());
String query="INSERT INTO player_sale(transaction_id,player_id,game_id,game_type_id,ticket_nbr,mrp_amt,deduct_from_bonus,
deduct_from_deposit,deduct_from_winning,good_cause_amt,vat_amt,taxable_sale,transaction_date,is_cancel)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);";
PreparedStatement pt = con.prepareStatement(query);
pt.setLong(1, 1);
pt.setLong(2, 110021);
pt.setInt(3, 1);
pt.setInt(4, 1);
pt.setLong(5, 12345678);
pt.setDouble(6, 10.00);
pt.setDouble(7, 20.00);
pt.setDouble(8,30.00);
pt.setDouble(9, 40.00);
pt.setDouble(10, 10.00);
pt.setDouble(11, 2.00);
pt.setDouble(12, 1.00);
pt.setTimestamp(13, transactionDate);
pt.setString(14, "N");
pstmt.executeUpdate();
}catch(Exception e){
e.printStackTrace();
}
Related
I am working on a app there are some JFormatedTextFields with mask formatted (##/##/#### as dd/MM/YYYY). I am trying to insert these date into Database but it is showing an error "Error Converting data type nvarchar to Date"
Error Converting data type nvarchar to Date
but I could not find any problem in my sql procedure because if I run that procedure using sql query analyzer it is working but if I try to execute from app it is showing error
here is my all codes
sql procedure
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Proc_set_ExamDeclaration]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Proc_set_ExamDeclaration]
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE Procedure [dbo].[Proc_set_ExamDeclaration]
(
#SchoolCode nvarchar (10),
#ClassCode nvarchar (4),
#GroupName nvarchar(50),
#ExamCode nvarchar (4),
#RegistationFess numeric(38,2),
#RegistatinStartDate date,
#RegistatinEndDate date,
#ExamStartDate date,
#ExamStatus nvarchar(10)
)
as
BEGIN
-- Insert statements for procedure here
Declare #RFirst as Date, #REnd as Date, #EStart as Date
set #RFirst = CONVERT(varchar, #RegistatinStartDate, 103)
set #REnd = CONVERT(varchar, #RegistatinEndDate, 103)
set #EStart = CONVERT(varchar, #ExamStartDate, 103)
IF NOT EXISTS (SELECT * FROM [dbo].[ExamDeclaration] where ClassCode = #ClassCode AND GroupName = #GroupName AND ExamCode = #ExamCode AND ExamStatus = 'Active')
BEGIN
INSERT INTO ExamDeclaration (SchoolCode, ClassCode,GroupName,ExamCode,RegistationFess,RegistatinStartDate,RegistatinEndDate,ExamStartDate,ExamStatus)
VALUES (#SchoolCode, #ClassCode,#GroupName,#ExamCode,#RegistationFess,#RFirst,#REnd,#EStart,#ExamStatus)
END
ELSE
Update ExamDeclaration
set RegistationFess = #RegistationFess,
RegistatinStartDate = #RFirst,
RegistatinEndDate = #REnd,
ExamStartDate = #EStart,
ExamStatus = #ExamStatus
Where ClassCode = #ClassCode AND GroupName=#GroupName AND ExamCode = #ExamCode
END
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
and here is the java codes
String School_Code = txt_SchoolCode.getText();
String ClassCode = txt_ClassCode.getText();
String groupName = com_groupname.getSelectedItem().toString();
String examCode = txt_ExamCode.getText();
String fees = txt_fees.getText();
String RStart = txt_RStart.getText();//((JTextField) txt_RStart.getDateEditor().getUiComponent()).getText();
String REnd = txt_REnd.getText();//((JTextField) txt_REnd.getDateEditor().getUiComponent()).getText();
String EStart = txt_ExamStart.getText();//((JTextField) txt_ExamStart.getDateEditor().getUiComponent()).getText();
String Estatus = com_eStatus.getSelectedItem().toString();
if(ClassCode.isEmpty() && examCode.isEmpty() && fees.isEmpty() /*&& RStart.isEmpty() && REnd.isEmpty() && EStart.isEmpty()*/){JOptionPane.showMessageDialog(null, "All Fields are Required !!");}
else{
try{
String sqlExamD = "Exec Proc_set_ExamDeclaration ?,?,?,?,?,?,?,?,?";
pst=conn.prepareStatement(sqlExamD);
pst.setString(1, School_Code);
pst.setString(2, ClassCode);
pst.setString(3, groupName);
pst.setString(4, examCode);
pst.setString(5, fees);
pst.setString(6, RStart);
pst.setString(7, REnd);
pst.setString(8, EStart);
pst.setString(9, Estatus);
pst.execute();
JOptionPane.showMessageDialog(null, "Saved Successfuly");
btn_new.doClick();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
any Idea where is the problem in my codes?
I am using java netbeans and sql server 2008
Thank you.
It looks to me that you have you assign your date variables in Java as strings, but you have them actually defined as dates:
String RStart = txt_RStart.getText();
...
#RegistatinStartDate date
And then you try to convert from date to varchar but assign it back to a date?
Declare #RFirst as Date
...
set #RFirst = CONVERT(varchar, #RegistatinStartDate, 103)
I'm trying to retrieve results from a Oracle 11.2.0.3 database like in the example given at http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html
String query = createQuery(); // SQL query to be used
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
System.out.println("output of first 10 results");
while(rs.next()){
if (i < 10){
String val1= rs.getString(1);
String val2 = rs.getString(8);
String val3 = rs.getString(13);
System.out.println("val1: " + val1 +
", val2: " + val2 + ", val3: " + val3);
}
i++;
}
However, some of the rows returned are different from when I run the same query in SQLDeveloper connected to the same DB schema.
Actually, some of the rows returned in the ResultSet do not match my query.
I am logging into the DB with the same user for both. The java application is using the ojdbc.jar provided at http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-112010-090769.html for the Oracle Database 11g Release 2 (11.2.0.3) JDBC Drivers
What could cause such a scenario to happen? There are no changes being made to the tables involved.
The sanitized query:
SELECT DISTINCT T1.COL1, T1.COL2, T1.COL3, T1.COL4, T1.COL5, T1.COL6, T1.COL7, T1.COL8, T1.COL9, COL10, T1.COL11, T1.COL12, T1.COL13
FROM VIEW1 T1, VIEW2 T2
WHERE T1.COL1 = T2.COL1
AND ( (NLSSORT(T1.COL8, 'NLS_SORT=BINARY_AI')=NLSSORT(TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')
AND T1.COL13<'Example')
OR (NLSSORT(T1.COL8, 'NLS_SORT=BINARY_AI')<NLSSORT(TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')) )
AND ( T2.ANOTHERCOL = 'SOMEVALUE' AND T1.COL1 = T2.COL)
ORDER BY NLSSORT(COL8, 'NLS_SORT=BINARY_AI') DESC, COL8 DESC, T1.COL13 DESC
In the output, I get:
val1: anid, val2: 2014-05-12 15:29:39, val3: doesnotmatter
As far as I'm aware, that row should not be returned since 2014-05-12 15:29:39 is not less than 2014-05-12 15:25:02. And indeed that row is not found when I run the query in SQLDeveloper.
I guess that col8 is of type date, and I think you problem is in
(NLSSORT(T1.COL8, 'NLS_SORT=BINARY_AI')=NLSSORT(TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')
your actions:
convert '2014...' to date
convert result to string
convert col8 to string using default format for date column
if your SQL Developer and your java client have different default format for date - you will get different result
I would recomend to change that line to
T1.COL8 = TO_DATE('2014-05-12 15:25:02', 'YYYY-MM-DD HH24:MI:SS')
Also, you don't need NLSSORT in WHERE clause, there is no sorting there.
Now I am thinking that I am wrong.. just don't want to delete it all :)
second try...
one date is 31322D6D61792D313400
another one is 31322D6D61792D313400
they are no less that the other
Query to check
select
NLSSORT(TO_DATE('2014-05-12 15:25:02',
'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI'),
NLSSORT(TO_DATE('2014-05-12 15:29:39',
'YYYY-MM-DD HH24:MI:SS'), 'NLS_SORT=BINARY_AI')
from dual
Any differences if instead of function, modify session?:
ALTER SESSION SET NLS_COMP = 'LINGUISTIC';
ALTER SESSION SET NLS_SORT = 'BINARY_AI';
I am trying to insert a record in a Oracle table using Java. The field in question is defined as a timestamp.
I am using a the following statement:
INSERT INTO MYTAB (UNIQUE_ID, CREATED_AT) VALUES ('137', ?)";
PreparedStatement updatePerf = connection.prepareStatement(updateString);
updatePerf.setTimestamp(1,getCurrentTimeStamp());
The getCurrentTimeStamp looks as follows:
private static java.sql.Timestamp getCurrentTimeStamp() {
long time = System.currentTimeMillis();
java.sql.Timestamp timestamp = new java.sql.Timestamp(time);
System.out.println("Time in milliseconds :" + timestamp);
return timestamp;
}
When the program runs, I still the correct timestamped printed with milliseconds:
Time in milliseconds :2014-05-13 15:40:03.076
However on the database, I only see
'137',2014-05-13 15:40:03
I want to retain the milliseconds desperately.
When you say "on the database, I only see", how are you getting the data out of Oracle? Have you proerly set NLS_TIMESTAMP?
Try setting:
NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH:MI:SS.FF'
in SQL*Plus, and then try the query, and see if you can see thw milliseconds component.
Alternately, you can format the timestamp column w/ a to_char() function:
select to_char(my_timestamp_col,'YYYY-MM-DD HH:MI:SS.FF') from my_table;
Note also, that if your column is timestamp with timezone, you'll need to set NLS_TIMETAMP_TZ_FORMAT instead.
I have a SQL Server query that I need to return all dates that are less that 90 days from the current. I thought this was quite trivial until the result set returned was completely wrong. Here's the query.
SELECT new_HwWarrantyEndDate
FROM TABLE
WHERE new_HwWarrantyEndDate IS NOT null
AND DATEDIFF(day,GETDATE(),new_HwWarrantyEndDate) <= 90;
Here are some of the results:
new_HwWarrantyEndDate
---------------------
2010-07-11
2012-12-09
2011-02-12
2012-12-09
2007-12-31
2007-12-31
2007-12-31
2007-12-31
How could this function return dates from years previous?
I have another issue.Why would a query such as:
SELECT DATEDIFF(day,GETDATE(),new_HwWarrantyEndDate) AS DateDiff
FROM TABLE
WHERE Diffdate IS NOT null;
Complain specifically DateDiff is not a valid column when I try and process the resultset ie:
result_set = stmt.executeQuery(query);
Date s;
if(!result_set.next()) {
System.out.println("Null set");
}
while(result_set.next()){
s = result_set.getDate("DateDiff");
System.out.println(s);
}
Thanks I don't have much experience with SQL Server. Any guidance would help.
In SARGable form;
SELECT new_HwWarrantyEndDate
FROM TABLE
WHERE new_HwWarrantyEndDate IS NOT NULL
AND new_HwWarrantyEndDate BETWEEN GETDATE() AND DATEADD(DAY, 90, GETDATE())
I'm supposed to add data from my csv file into my database. I have no problem adding data into the database, however, I have a situation where my java program has to add new values or update current values into the database, say under my column "date". When a new data is not identified in my current database, it would be added. However, under the same row, there's a column called "demand". If the date is the same but the demand is different. It would have to be updated. At the moment, my script can only retrieve the data line by line from mysql and compare with the data collected from the csv file. When the date is different, it can add the data into a new row. The problem is that the java program that I created can only read line by line from the beginning. I would have a repetition of data because when it start comparing from the earliest data to the latest. For example, my earliest date is 01 jan and it is compared to my csv data say 31 jan. However, my later entries has a 31 jan already stored. But my java program continue to add this data in because it compared from the beginning. I will explain in greater detail if you need more information.
public void readDataBase(int val, String d1, String d2, String d3, String d4 ) throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/testdb?"
+ "user=root&password=");
statement = connect.createStatement();
resultSet = statement.executeQuery("SELECT COUNT(*) FROM testdb.amg");
while (resultSet.next()) {
total = resultSet.getInt(1);
}
resultSet = statement.executeQuery("select * from testdb.amg");
try{
int id;
String Date,Demand;
while (resultSet.next()) {
id = resultSet.getInt("id");
Date = resultSet.getString("Date");
Demand = resultSet.getString("Demand");
System.out.println("total: " + total);
System.out.println("d4: " + d4);
if (!Date.equals(d1) && !Demand.equals(d3))
{
int val1 = total +1;
preparedStatement = connect
.prepareStatement("insert into testdb.amg values (?, ? ?)");
preparedStatement.setInt(1, val1);
preparedStatement.setString(2, d1);
preparedStatement.setString(3, d3);
preparedStatement.executeUpdate();
System.out.println("UpdatedII");
}
Identify the distinct columns in your database (date + demand + whatever_is_distinct ) and define a UNIQUE constraint on that combination.
By doing that ,during insertion, if there is any Constraint Violation exception that gets thrown , update that record or else the record gets inserted.
As Rocky said, define the unique key on the table. Since the database is MySQL, you can achieve what you want by simple query with INSERT... ON DUPLICATE KEY UPDATE ... INSERT ... ON DUPLICATE KEY UPDATE Syntax
In your case it can be
insert into testdb.amg values (?, ? ?) on duplicate key update <update fields here>
So the final query shall be
"insert into testdb.amg values (?, ?, ?) on duplicate key update Demand=?"
and add
preparedStatement.setString(4, d3);