【问题标题】:BasicNameValuePair (String, java.lang.String) in BasicNameValuePair cannot be applied无法应用BasicNameValuePair中的BasicNameValuePair(String, java.lang.String)
【发布时间】:2015-07-17 12:46:50
【问题描述】:

我目前正在使用此代码在数据库中存储两个字符串(newCategory 和 reportDate):

String newCategory = spinnerFood.getSelectedItem().toString();

            // Create an instance of SimpleDateFormat used for formatting
            // the string representation of date (month/day/year)
            DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
            // Get the date today using Calendar object.
            Date today = Calendar.getInstance().getTime();
            // Using DateFormat format method we can create a string
            // representation of a date with the defined format.
            String reportDate = df.format(today);

            // Preparing post params
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("name", newCategory));
            params.add(new BasicNameValuePair("dtime", reportDate));

            ServiceHandler serviceClient = new ServiceHandler();

            String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
                    ServiceHandler.POST, params);

这将成功存储名称字符串。但是数据库中的日期和时间数据包含值:

0000-00-00 00:00:00

如果我将日期字符串更改为日期/时间格式,如下所示:

df.format(today);

        params.add(new BasicNameValuePair("dtime", today));

我得到错误:

BasicNameValuePair中的BasicNameValuePair(String, java.lang.String)不能应用

到(字符串,java.util.date)

谁能告诉我如何将日期和时间值存储到数据库中?

【问题讨论】:

  • Timestamp 存储日期和时间。
  • 在这种情况下如何使用 Timestamp?
  • 查看我的更新答案。
  • 无效的DATEDATETIMETIMESTAMP 值将转换为相应类型的zero 值。就像上面你说的那样。 @西林
  • 好的。但是这段代码中的 rs 和 index 代表什么:java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(index);//now retrieve here 抱歉,我是 java 新手..

标签: java mysql date


【解决方案1】:

您可以将日期和时间作为格式化字符串添加到params

 params.add(new BasicNameValuePair("dtime", reportDate));

然后,您处理 db 调用的代码将使用 mysql 函数 STR_TO_DATE(...) 将字符串格式化为所需的 DateTime。

【讨论】:

    【解决方案2】:
    java.util.Date dt = new java.util.Date();
    
    java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    String currentTime = sdf.format(dt);//current date and time here, '2015-07-17 18:38:46'
    
    params.add(new BasicNameValuePair("dtime", currentTime));//now pass here
    

    现在将此值存储到mysql db,其列类型为timestamp。 现在在此处使用jdbc 代码从数据库中检索数据。

      java.sql.Timestamp dbSqlTimestamp = rs.getTimestamp(index);//now retrieve here
    

    For more?

    【讨论】:

      【解决方案3】:

      我发现如果你想创建一个连接数据库并存储当前时间的应用程序,那么你最好在你的 sql 表中创建一个 Timestamp 列,并将其值设置为 CURRENT_TIME。您实际上不需要在程序中获取当前时间,然后将其发送到您的表。您可以将所需的任何数据发送到表,然后此 Timestamp 列将存储您将该数据发送到表的当前时间。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-11
        • 1970-01-01
        • 1970-01-01
        • 2015-02-20
        • 2023-03-24
        相关资源
        最近更新 更多