当前位置: 代码迷 >> java >> 无法应用BasicNameValuePair中的BasicNameValuePair(字符串,java.lang.String)
  详细解决方案

无法应用BasicNameValuePair中的BasicNameValuePair(字符串,java.lang.String)

热度:33   发布时间:2023-07-31 11:07:38.0

我目前正在使用此代码在数据库中存储两个字符串(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(字符串,java.lang.String)

到(String,java.util.date)

有人可以告诉我如何将日期和时间值存储到数据库吗?

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

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

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

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

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

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

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

  相关解决方案