Solved

How can I insert DATE today into a database?

Posted on 2008-10-21
5
238 Views
Last Modified: 2012-05-05
I tried this but there is error:

            Calendar cal = Calendar.getInstance();
            while (uprs.next())
            {              
            uprs.updateTime("datecol", cal.getTime());
            uprs.updateRow();        
            }
0
Comment
Question by:glynco
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
5 Comments
 
LVL 6

Expert Comment

by:javaexperto
ID: 22772812
The first line you format the date in order to match the format in your database
second line just get the current time.
third line put into a String the formated date.



SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
Date currentTime = c.getTime();
String dateString = formatter.format(currentTime);
 
//To insert only append the date String. For example:
statement.executeUpdate("INSERT INTO mesa_venta values(" + date + ")");

Open in new window

0
 

Author Comment

by:glynco
ID: 22772906
Still not working. Here is the code, no errors but the date is not added to the database.

 
 
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
 
public class DemoPreparedStatementSetDate
{
    public static void main(String[] args) throws Exception
    {
        Connection con = null;
        try
        {
            // Here we load the MySQL database Driver class
            Class.forName("com.mysql.jdbc.Driver");
 
            // Define properties for connecting to database such as
            // database jdbc url, username and password
            String url = "jdbc:mysql://localhost/datedb";
            String username = "root";
            String password = "root";
 
 
            con = DriverManager.getConnection(url, username, password);
                        Statement statement = con.createStatement();
            
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT * FROM datetable");
          
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
Date currentTime = cal.getTime();
String dateString = formatter.format(currentTime);
 
while (uprs.next())
            {
 
 
//To insert only append the date String. For example:
statement.executeUpdate("INSERT INTO date_column values(" + dateString + ")");
uprs.updateRow();
            }
 
        } 
          
        
        finally {
            if (con != null && !con.isClosed())
            {
                con.close();
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:glynco
ID: 22772922
Solved.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
 
public class DemoPreparedStatementSetDate {
  public static java.sql.Date getCurrentJavaSqlDate() {
    java.util.Date today = new java.util.Date();
    return new java.sql.Date(today.getTime());
  }
 
  public static Connection getConnection() throws Exception {
    String driver = "org.gjt.mm.mysql.Driver";
    String url = "jdbc:mysql://localhost/datedb";
    String username = "root";
    String password = "root";
    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }
 
  public static void main(String[] args) throws Exception {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = getConnection();
      String query = "insert into datetable(id, date_column) values(?, ?)";
      pstmt = conn.prepareStatement(query);
      pstmt.setString(1, "0001");
      java.sql.Date date = getCurrentJavaSqlDate();
      pstmt.setDate(2, date);
 
      // execute query, and return number of rows created
      int rowCount = pstmt.executeUpdate();
      System.out.println("rowCount=" + rowCount);
    } finally {
      pstmt.close();
      conn.close();
    }
  }
}

Open in new window

0
 
LVL 6

Expert Comment

by:javaexperto
ID: 22772927
In my case I have a DateTime column so if you only have a date try this:


SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd");

Open in new window

0
 
LVL 6

Accepted Solution

by:
javaexperto earned 500 total points
ID: 22772941
Well, please check my answers I gave you the solution
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Custom Java Application connects to database: Which one of the 20? 4 58
glassfish admin console 1 53
learn programming 8 95
Delete .class files at every compile 4 58
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses

751 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question