java 使用 PreparedStatement 将日期插入 MySQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12916262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 10:46:24  来源:igfitidea点击:

Inserting date into MySQL database using a PreparedStatement

javajdbcprepared-statement

提问by ankur jadiya

I want to update the string date into MySQL database using prepared statement. I have tried a lot and always got error java.util.Date cannot parse into java.sql.Dateor vise versa. I didn't import anything here. Please import according to your answer.

我想使用准备好的语句将字符串日期更新到 MySQL 数据库中。我尝试了很多,但总是出错java.util.Date cannot parse into java.sql.Date,反之亦然。我没有在这里导入任何东西。请根据您的回答导入。

public class Date1 
{ 
    public static void main(String args[]) 
    {
        String source="2008/4/5";              
        SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");                       
        java.sql.Date d=(Date) format.parse(source);             
        Class.forName("com.mysql.jdbc.Driver");        
        Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");   
        PreparedStatement ps=con.prepareStatement("insert into ankur1 values(?)");          
        ps.setDate(1,(java.sql.Date) d);    
        ps.executUpdate();
    }
}

回答by Lukas Eder

Write this

写这个

java.sql.Date d= new java.sql.Date(format.parse(source).getTime());

instead of this:

而不是这个:

java.sql.Date d=(Date) format.parse(source);

Because you cannot just cast java.util.Dateto its subtype java.sql.Date. You have to convert it. Do also note that your format string doesn't match your actual date format, as Bill the Lizard commented.

因为你不能只是转换java.util.Date到它的 subtype java.sql.Date。你必须转换它。另请注意,正如比尔蜥蜴评论的那样,您的格式字符串与您的实际日期格式不匹配。

回答by Java D

java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());

pstmt.setTimestamp(1, date);

Try this it may work.. Thanks

试试这个它可能工作..谢谢

回答by Yang_2333

here is another simpler way to solve this:

这是解决此问题的另一种更简单的方法:

preparedStatement = connect.prepareStatement("INSERT INTO test.TABLENAME VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)"); 

Or, you can replace the "?" with real data.

或者,您可以替换“?” 用真实数据。

This is how I insert date and time to mySQL, just figured it out.

这就是我向 mySQL 插入日期和时间的方式,刚刚弄清楚了。

We can adjust the kinds of parameters to meet our data's format, it's easy and clean.

我们可以调整参数的种类来满足我们的数据格式,它既简单又干净。