Cant insert an empty date value into mysql - java

String datum = datumInvoer.getText();
**String bdate = bdatumInvoer.getText();**
String[] speler = spelers.getSelectedItem().toString().split(" ");
String[] toernooi = toernooien.getSelectedItem().toString().split(" ");
try {
PreparedStatement query = con.prepareStatement("INSERT INTO `fullhouse`.`inschrijving_toernooi` ( `IT_datum`, `IT_betaaldatum`, `speler`, `toernooi`) VALUES (?, ?, ? ,?)");
query.setString(1, datum);
query.setString(2, bdatum);
query.setString(3, speler[0]);
query.setString(4, toernooi[0]);
query.execute();
i have set the default to NULL , but it still wont insert it i am close to changing the datatype to varchar.
ERROR: incorrect date value
delimiter $$
CREATE TABLE `inschrijving_toernooi` (
`IT_code` int(11) NOT NULL AUTO_INCREMENT,
`IT_datum` date DEFAULT NULL,
`IT_betaaldatum` date DEFAULT NULL,
`speler` int(11) NOT NULL,
`toernooi` int(11) NOT NULL,
PRIMARY KEY (`IT_code`),
UNIQUE KEY `aaa` (`speler`,`toernooi`),
KEY `FS_code_idx` (`speler`),
KEY `FT_code_idx` (`toernooi`),

First Convert your date parameter from string to date. For that follow code below.
String bdate = bdatumInvoer.getText();
// get the correct date Format
// follow the link to get correct date format
// throws ParseException
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(bdate);
Class SimpleDateFormat API
Now in prepared statement set them as date like shown below. As your table structure allows date in table.
query.setDate(2, date);
Now you still want to set null to that column then you can use and tell your query to set null by using following format in prepared statement.
query.setNull(2, java.sql.Types.DATE);
OR
query.setDate(2, null);
setNull API
Mapping of java.sql.Types to SQL types
I think this will solve your issue.

You need to change how you are passing parameters to you prepared statement
It should be something like below. And datum and bdatum should be of type Date. If you do not use what types are defined in your db you could put pass invalid data to your sql which would cause exceptions.
query.setDate(1, datum);
query.setDate(2, bdatum);
query.setInt(3, speler[0]);
query.setInt(4, toernooi[0]);

I suspect your bdatum variable contains an empty string. If you want to insert a SQL null, you need to pass in null, not empty string. (When I tried this on my machine with a similar insert, I got an "Incorrect date value" when trying to insert an empty string, but not with a null.)
if ("".equals(bdatum))
bdatum = null;
ps.setString(2, bdatum);
When you pass in a string in JDBC for a date value, MySQL will try to parse it, but empty string ("") is not a valid value. This works similarly to if you tried to do an insert with a date literal:
INSERT INTO `some_table` (`some_nullable_date_column`) VALUES ('2000-01-01') -- this works
INSERT INTO `some_table` (`some_nullable_date_column`) VALUES (NULL) -- this works
INSERT INTO `some_table` (`some_nullable_date_column`) VALUES ('') -- this fails
As an aside, passing in a string for a date value is semantically wrong and possibly less robust than parsing the string to a Date object before passing it to the PreparedStatement.

Related

How to automatically insert date and time into sql table

I've created a table name EventLog7 in SQL Server 2008 :
create table EventLog7(
EventId int not null identity(1,1),
EventDate datetimeconstraint DF_myDate DEFAULT (getdate()),
ObjectId varchar(50),
Name varchar(50),
Value varchar (50)
)
In NetBeans, there are three jtextfields which help to insert data into EventLog SQL Table (ObjectId, Name, Value) when I press the button.
Mentioned below action button code:
String objectid=jTextField1.getText();
String value=jTextField2.getText();
String name=jTextField3.getText();
try{
DoConnect();
st=conn.createStatement();
String sql = "insert into EventLog7 values('"+objectid+"','"+name+"','"+value+"')";
pst = conn.prepareStatement(sql);
pst.execute();
rs=st.executeQuery("select * from EventLog7");
jTable1.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
So, i want that when I insert values of ObjectId,Name,Value in three jtextfiles then Sql table will insert automatically date and time with these data.
But according to my code, it's showing error
Column names or number of supplied values does not match table definition
So please provide me right way.
String sql = "insert into EventLog7 values('"+objectid+"','"+name+"','"+value+"')";
line will be
String sql = "insert into EventLog7(ObjectId, Name, Value, EventDate) values('"+objectid+"','"+name+"','"+value+"',GETDATE())";
I do not know how the IDs is generated sql-server , you may need to set it as well if that is not auto assign/increment.
And I can say this is not secure, you need to use ?s instead of your variables and use set methods to set them as a_horse_with_no_name reminds. Use what I suggested only for mitigating the error you have now.

GetString of Composite Type Postgres?

I created this table:
CREATE TABLE public.luogo
(
id_luogo integer NOT NULL DEFAULT nextval('luogo_id_luogo_seq'::regclass),
tipo character varying(30) NOT NULL,
indirizzo indirizzo,
CONSTRAINT luogo_pk PRIMARY KEY (id_luogo)
)
where indirizzo type is
CREATE TYPE public.indirizzo AS
(
citta character varying(50),
via character varying(50),
cap integer,
civico integer
);
So I'm using JDBC and I need this query
"SELECT * FROM luogo WHERE id_luogo= '"+variable+"'";
The problem is that resultset.getstring("indirizzo") returns obviously a string like: "(value,value,value)". How to get as string the singular parameters of indirizzo?
The correct SQL syntax is:
"SELECT id_luogo,(indirizzo).citta FROM luogo"
To get the String in Java is: resultset.getString("citta")

How to use PreparedStatement with foreign key

I am working in a project of employees Attendance in Java (using NetBeans), I have created two tables, one for employee's data and the other to check the attendance.
Now I want to link the primary key of the first table to the second table but I do not know how. For example if you want to check the attendance it will show you the ID of the employee and when (time in / time out).
What I have tried:
This is the first table:
create table employee (
empID int primary key auto_increment,
fName varchar(100),
civilId int,
mobile int
);
The second table:
create table employeeAttendance (
id int primary key auto_increment,
empID int not null,
timeIn time,
timeOut time,
daay date,
constraint emp_fk foreign key (empID) references employee (empID)
);
and in Java I did that but could not complete it :
String sql="insert into employeeAttendance(empID,timeIn,daay)values(?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1,.getText());
pstmt.setString(2,timeLabel.getText());
pstmt.setString(3,dateLabel.getText());
You did almost everything right in terms of functionality.
Please don't use text fields for integer and date if you can avoid it. Every major UI Framework has fields for this special types, so use them!
However, you should use the correct setter method of PreparedStatement. If your column is an int you should use ps.setInt, if you have a time/timestamp/date column you should use ps.setDate.
So your Java code would look like this
SimpleDateFormatter sdf = new SimpleDateFormatter("dd.MM.yyyy");
java.util.Date jtimeIn = sdf.parse(timeLabel.getText());
java.sql.Date stimeOut = new java.sql.Date(jdate.getTime()); //This part is important, jdbc uses java.sql.Dates!
java.util.Date jdaay = sdf.parse(dateLabel.getText());
java.sql.Date sdaay = new java.sql.Date(jdaay.getTime()); //This part is important, jdbc uses java.sql.Dates!
String sql="insert into employeeAttendance(empID,timeIn,daay)values(?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,Integer.parseInt(empIDAsText));
pstmt.setDate(2,stimeOut);
pstmt.setString(3,sdaay);

How to tell if timestamp from Postgres in Java is null

The code below is a snippet from a back-end REST service I have touched on. I'm wondering how to tell if a timestamp I'm getting is null. I've learned through trial and error that if the timestamp is null in the Postgres database that when I bring it into Java that if its null it will get instantiated as a new DateTime at the current time of operation. What can I do to check get and set nulls dynamically according to model data?
public List<SubscriptionEntityModel> getAllSubscriptions(PagingInfoDomainModel paging) throws Exception {
Database db = new Database();
String stmt = "{call sp_subscriptions_get_all(?, ?)}";
if(AppConfig.data.isDebug) {
logger.debug("Running database operation.. " + stmt);
}
CallableStatement sproc = db.dbEndpoint.prepareCall(stmt);
sproc.setInt(1, paging.pageCurrent);
sproc.setInt(2, paging.pageItemCount);
ResultSet rs = sproc.executeQuery();
List<SubscriptionEntityModel> subscriptions = new ArrayList<SubscriptionEntityModel>();
while(rs.next()) {
SubscriptionEntityModel subscription = new SubscriptionEntityModel();
subscription.subscriptionId = rs.getInt("subscription_id");
subscription.name = rs.getString("name");
subscription.emailAddress = rs.getString("email_address");
subscription.phoneNumber = rs.getString("phone_number");
subscription.organizationId = rs.getInt("organization_id");
subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));
subscription.expiredAt = new DateTime(rs.getTimestamp("expired_at"));
subscriptions.add(subscription);
}
sproc.close();
db.destroy();
return subscriptions;
}
Check out ResultSet#wasNull
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#wasNull()
Reports whether the last column read had a value of SQL NULL.
Hence you can use it after rs.getTimestamp() to check if the value read was SQL NULL, but note that ResultSet#getTimestamp already returns a null reference if that was the case.
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#getTimestamp(int)
the column value; if the value is SQL NULL, the value returned is null
The problem you're facing is that when you pass a null reference to the constructor of DateTime, it will be interpreted as now.
java.sql.Timestamp getTimestamp(String columnLabel) throws SQLException;
will return null if the SQL field is NULL.
The problem is the way you instantiate your DateTime object.
With JodaTime (I give this example as you don't specify the used library), executing the following code creates indeed a DateTime instance with the actual date time :
java.sql.Timestamp timestamp = null;
DateTime dateTime = new DateTime(timestamp);
So to solve your problem, what you could do is checking the returned value by the resultset.
If it is not null, use it to create the DateTime object.
Otherwise don't use it and leave to nullthe DateTime field of the SubscriptionEntityModel you are setting properties.
So instead of doing :
subscription.createdAt = new DateTime(rs.getTimestamp("created_at"));
You should do :
java.sql.Timestamp createdAt = rs.getTimestamp("created_at");
if (createdAt != null){
subscription.expiredAt = new DateTime(createdAt);
}

Date format in an Oracle stored procedure called from Java

I am trying to use an Oracle stored procedure to update a database table. I am calling the procedure from a Java program. I want my procedure to accept dates in the format '01-01-2015' but for some reason my procedure will only accept a date if it is formatted as '01-JAN-2015'.
My stored procedure:
DELIMITER //
CREATE OR REPLACE PROCEDURE updateAward
(
p_award_id IN awards.award_id%TYPE,
p_award_date IN awards.award_date%TYPE,
p_total_amount IN awards.total_amount%TYPE,
p_number_sales IN awards.number_sales%TYPE,
p_emp_id IN awards.emp_id%TYPE
)
AS
BEGIN
UPDATE awards
SET award_date = to_date(p_award_date, 'DD-MM-YYYY'),
total_amount = p_total_amount,
number_sales = p_number_sales,
emp_id = p_emp_id
WHERE award_id = p_award_id;
COMMIT;
END;
/
The java code that calls it:
public boolean updateByID(Connection conn, String strVar, int[] intVar, double doubleVar)
{
System.out.println(strVar);
System.out.println(doubleVar);
System.out.println(intVar[0]);
System.out.println(intVar[1]);
System.out.println(intVar[2]);
try
{
String query = "{call updateAward(?,?,?,?,?)}";
CallableStatement stmt = conn.prepareCall(query);
stmt.setInt(1,intVar[0]);
stmt.setString(2, strVar);
stmt.setDouble(3, doubleVar);
stmt.setInt(4, intVar[1]);
stmt.setInt(5, intVar[2]);
stmt.executeUpdate();
return true;
}
catch(SQLException e)
{
System.out.println(e.getMessage());
}
return false;
}
The console print out of the variables being passed:
12-12-2012
65165.2
21
22
3
The error itself:
KORA-01843: not a valid month
ORA-06512: at line 1
Every solution that I have found has been to put the date format in the procedure. I believe I have done it with
award_date = to_date(p_award_date, 'DD-MM-YYYY'),
Have I written it incorrectly? Can someone please help?
Currently you are passing a String:
stmt.setString(2, strVar);
And you are parsing a String:
award_date = to_date(p_award_date, 'DD-MM-YYYY')
But you are expecting a Date in your custom type, and that is where the conversion fails. Change that to VARCHAR (or VARCHAR2) and it will work.
You're passing a string to a procedure that's expecting an Oracle date argument, via setString(). That means Oracle has to do an implicit conversion of the string to a date as part of the call, using the session/locale NLS_DATE_FORMAT, before you reach your to_date() call.
You could change your procedure argument type from awards.award_date%TYPE to varchar2, and still do the explicit conversion inside the procedure. Or you can leave the procedure signature as it is and pass the correct data type by converting it on the Java side, e.g.:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
cStmt.setDate(2, new java.sql.Date(sdf.parse(strVar).getTime()));
And as p_date is already a date, you should not call to_date() on that, as it will do an implicit conversion back to a string (using NLS_DATE_FORMAT again) and then try to explicitly convert that back to a date using the format model you supplied, which is also likely to give a similar error. Simplify that to just:
SET award_date = p_award_date,

Categories