Link to home
Start Free TrialLog in
Avatar of searchsanjaysharma
searchsanjaysharma

asked on

How to convert string value of date time into date time so that it can be inserted into datetime field

class sqlsave
{
      public static void main(String args[]) throws Exception
      {
            Connection con;

            Statement  stmt;
            ResultSet res;
            
            String driver="sun.jdbc.odbc.JdbcOdbcDriver";
            String url="jdbc:odbc:mydsn";
            String userid="";
            String password="";
            
            int teno = 6;
            String tename="Kapil";
            String tcity="Fazilka";
      
      try
      {
            Class.forName(driver);      
            con = DriverManager.getConnection(url,userid, password);

            String s;
            s = "insert into emp(eno,name,city,doj) values("+teno+",'"+tename+"','"+tcity+"')";
            stmt = con.createStatement();
            stmt.executeUpdate(s);
            stmt.close();
            con.close();
      }
      catch(SQLException ex)
      {
      System.out.println("Error");
      }
      }
}


How to insert date time value from textbox into database having datetime data type in sql server.
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

For SQL server, I would send the data as ODBC canonical format, which is 'yyyy-mm-dd hh:mi:ss' in SQL terms. In Java, you can achieve this format using "yyyy-MM-dd HH:mm:ss".

For example:
java.text.Format sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date_for_sql = sdf.format(new java.util.Date("3/12/13 13:00"));

The Date constructor with string parameter is deprecated, but it was an easy way to get my point across. You convert the string you have to a date object in Java, but pass a formatted string to SQL. I just find it easier, but you can use a similar approach to get a java.sql.Date object using valueOf(). The key is to pass date like "2013-06-20".
http://docs.oracle.com/javase/6/docs/api/java/sql/Date.html#valueOf(java.lang.String)
Avatar of searchsanjaysharma
searchsanjaysharma

ASKER

java.util.Date now=new java.util.Date();
SimpleDateFormat formatter=new SimpleDateFormat("dd/MM/yyyy hh:mm:ss" );
System.out.println(formatter.format(now));

How to insert this kind of value in table.
Use a PreparedStatement ps and call ps.setTimestamp or ps.setDate

As has been stated above by  mwvisa1,java.sql.Date.valueOf can be used, or use java.sql.Timestamp.valueOf
ASKER CERTIFIED SOLUTION
Avatar of Valeri
Valeri
Flag of Bulgaria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You have to use parse, not format!
Yes, that was just a typo on  mwvisa1's part most probably.  searchsanjaysharma knows which way the conversion is to go, as evidenced by the title of the question
?