【问题标题】:for loop statement to create rows in databasefor循环语句在数据库中创建行
【发布时间】:2014-04-08 19:14:21
【问题描述】:

我正在尝试使用for循环语句如下:

for(int i=1; i <= 48; i++) { insertdiary("", ""); }

在我的 MyDB 文件中:

package com.cookbook.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.util.Log;

public class MyDB {
    private SQLiteDatabase db;
    private final Context context;
    private final MyDBhelper dbhelper;



    // Initializes MyDBHelper instance
    public MyDB(Context c){

        context = c;
        dbhelper = new MyDBhelper(context, Constants.DATABASE_NAME, null,
                                            Constants.DATABASE_VERSION);

    }


    // Closes the database connection
    public void close()
    {
        db.close();
    }

    // Initializes a SQLiteDatabase instance using MyDBhelper
    public void open() throws SQLiteException
    {

        try {
            db = dbhelper.getWritableDatabase();
        } catch(SQLiteException ex) {
            Log.v("Open database exception caught", ex.getMessage());
            db = dbhelper.getReadableDatabase();
        }
    }


    // Saves a diary entry to the database as name-value pairs in ContentValues instance
    // then passes the data to the SQLitedatabase instance to do an insert
    public long insertdiary(String title, String content)
    {

        try{
            ContentValues newTaskValue = new ContentValues();
            newTaskValue.put(Constants.TITLE_NAME,  title);
            newTaskValue.put(Constants.CONTENT_NAME, content);
            newTaskValue.put(Constants.DATE_NAME,     java.lang.System.currentTimeMillis());            
            return db.insert(Constants.TABLE_NAME,  null, newTaskValue);
        } catch(SQLiteException ex) {
            Log.v("Insert into database exception caught",
                    ex.getMessage());
            return -1;
        }

    }

    // updates a diary entry (existing row)
        public boolean updateDiaryEntry(String title, long rowId)
        {

            ContentValues newValue = new ContentValues();
            newValue.put(Constants.TITLE_NAME, title);

            return db.update(Constants.TABLE_NAME, newValue, Constants.KEY_ID + "=" +     rowId, null)>0;

        }

    // Reads the diary entries from database, saves them in a Cursor class and returns     it from the method
    public Cursor getdiaries()
    {
        Cursor c = db.query(Constants.TABLE_NAME, null, null,
                            null, null, null, null);
        return c;
    }

}

我的目标是在首次创建数据库或表时创建 48 个空行,以便我可以进一步更新这些行而不是创建新条目。不幸的是,我使用此代码的尝试很不幸地给了我错误或创建了多于 48 行的行。 有没有人可以帮助我在第一次创建数据库或表时使用此代码创建 48 行? 我感谢所有帮助。 稻谷

【问题讨论】:

  • “我的目标是在第一次创建数据库或表时创建 48 个空行,这样我就可以进一步更新这些行而不是创建新条目。” 这总是一个坏主意当您使用数据库时。只需在数据准备好时插入行。
  • 创建“未使用的行”的问题是您需要到处代码来检查“行”是否未使用!在需要时创建一行的成本与所有“检查”代码的成本相比是不值得的!也就是说,如果你得到一行,那么你可以确定它包含有用的数据!
  • 创建 48 行没有内容或有一些内容但允许更新它们而不是创建新行怎么样?我这边的问题是我需要将edittext字段分配给相应的行,我将通过它们的id.s来识别行
  • 瑞安文森特。对我来说,重要的是空行被分配给特定的编辑文本字段并代表时间表中的一个时间块。
  • 是的,我很欣赏这个问题。您希望保留一段时间。没问题,有一个记录时间段及其状态的表(主)。将其移至“详细信息表”以在需要时找到“实际”“时隙”使用。

标签: mysql sql database loops rows


【解决方案1】:

除非确实有一些严格的规则来管理创建 48 个空行的要求,否则创建它们确实是绝对错误的做法。当您需要将数据插入其中时,根据需要创建它们。

【讨论】:

  • 我需要有 48 行对应于 edittext 字段来更新这些行,就像在日记中一样。每行代表一天中的特定时间。我无法在需要时创建新行,因为它们将从最旧到最新排序,这不是预期的......
  • 如果不创建 48 个“空”行,那么是否有另一种解决方法将 edittext 与特定行链接?
  • 等等,您有一个日记应用程序,该应用程序有一个带有预定义时间块的时间表。文本存储在一个单独的表中,链接到时间块表,您想在文本表中创建 48 条记录,每条记录对应于时间表中的一个时间条目?对吗?
  • 一个日记应用程序,它有一个带有预定义时间块的时间表。文本通过插入或更新日记编辑文本字段存储到表中的相应行(预定义的 48 行表,初始数据或无数据)。 Listview 将行放在我的时间表中的列表中,因此每一行对应于每个时间块。
【解决方案2】:

我最初是在 mysql 中做的。创建 SQLFiddle 时遇到问题,所以我也创建了 SQLite 版本。

有一个SQLFiddle。将后面的所有内容压缩到 8K(SQLFiddle 限制)中,这很“有趣”;-/

SQLite 版本,除了“创建表”语句之外完全相同,如果需要,我将提供。这将是数据库文件的下载,这在所有机器上都是相同的。如果需要,我也可以提供创建脚本。

目的:

据我所知,这个想法是显示“约会”,将一天分为 48 到 30 分钟的时段。

要求仅记录实际约会。

我把它想象成一小部分部门,在事件发生的一天记录约会。在我的示例数据中,人们访问。

这是显示约会的查询:

SELECT * 
FROM department_appointments_view dav
WHERE dav.the_date = '2014-04-11'
 AND  dav.department_id  = 1
 AND  dav.time_slot_id BETWEEN 12 AND 20;

这是示例输出:

appointment_id  department_id  department_code  the_date             time_slot_id  start_time  attendee           reason                 duration  
--------------  -------------  ---------------  -------------------  ------------  ----------  -----------------  ---------------------  ----------
             0              1  dept_01          2014-04-11 00:00:00            12  05:30:00                                                      30
             0              1  dept_01          2014-04-11 00:00:00            13  06:00:00                                                      30
             1              1  dept_01          2014-04-11 00:00:00            14  06:30:00    Catherine Tramell  to see you                     30
             0              1  dept_01          2014-04-11 00:00:00            15  07:00:00                                                      30
             2              1  dept_01          2014-04-11 00:00:00            16  07:30:00    Buddy Ackerman     to see them                    30
             0              1  dept_01          2014-04-11 00:00:00            17  08:00:00                                                      30
             0              1  dept_01          2014-04-11 00:00:00            18  08:30:00                                                      30
             3              1  dept_01          2014-04-11 00:00:00            19  09:00:00    Ivan Drago         to visit someone else          30
             0              1  dept_01          2014-04-11 00:00:00            20  09:30:00                                                      30

因此,输入约会的主表是:

CREATE TABLE `department_appointments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_id` int(11) NOT NULL,
  `the_date` date NOT NULL,
  `time_slot_id` int(11) NOT NULL,
  `attendee` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `reason` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `duration` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `dept_fk` (`department_id`),
  CONSTRAINT `dept_fk` FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

这是唯一输入约会信息的表格。

样本数据:

    id  department_id  the_date    time_slot_id  attendee                 reason                 duration  
------  -------------  ----------  ------------  -----------------------  ---------------------  ----------
     1              1  2014-04-11            14  Catherine Tramell        to see you                     30
     2              1  2014-04-11            16  Buddy Ackerman           to see them                    30
     3              1  2014-04-11            19  Ivan Drago               to visit someone else          30

我们需要一些支持表:

部门表:

CREATE TABLE `departments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `department_code` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

样本数据:

   id  department_code  title                        
------  ---------------  -----------------------------
     1  dept_01          Dept 01 - The Widget Makers  
     2  dept_02          Dept 02 - For Bar Workers    

日历:这只是一个包含日期的表格。我的测试数据是四月份的。

CREATE TABLE `the_calendar` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `the_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Sample data:
    id  the_date             
------  ---------------------
     1  2014-04-01 00:00:00  
     2  2014-04-02 00:00:00  
     3  2014-04-03 00:00:00  
     4  2014-04-04 00:00:00  

read_only_time_slots 表。这有 48 行,其中包含开始时间。此表是只读的,从未更新或复制或任何东西。

CREATE TABLE `read_only_time_slots` (
  `time_slot_id` int(11) NOT NULL,
  `start_time` time NOT NULL,
  `duration` int(11) NOT NULL,
  PRIMARY KEY (`time_slot_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

样本数据:

time_slot_id  start_time  duration  
------------  ----------  ----------
           1  00:00:00            30
           2  00:30:00            30
           3  01:00:00            30


----------------------

您现在需要一些查询来运行这个批次。请注意,我们尽可能利用数据库引擎进行笛卡尔积。它会从上面的表格中为我们生成所有需要的行。

现在,为了简化信息的使用,我使用了“视图”。这样我的困惑就少了。

观点

第一个是:time_slot_view

CREATE VIEW `time_slot_view` AS (
SELECT ts.time_slot_id  AS time_slot_id,
       ts.start_time    AS start_time,
       ts.duration      AS duration
FROM read_only_time_slots ts 
ORDER BY ts.time_slot_id ASC)

接下来是:department_calendar_view

这将返回每个部门每天的空时隙。

CREATE VIEW `department_calendar_view` AS (
SELECT
  `d`.`id`              AS `department_id`,
  `d`.`department_code` AS `department_code`,
  `c`.`the_date`        AS `the_date`,
  `tsv`.`time_slot_id`  AS `time_slot_id`,
  `tsv`.`start_time`    AS `start_time`,
  `tsv`.`duration`      AS `duration`
FROM ((`the_calendar` `c`
    JOIN `time_slot_view` `tsv`)
   JOIN `departments` `d`)
ORDER BY `d`.`department_code`,`c`.`the_date`,`tsv`.`time_slot_id`)

最后:有一个使用以上所有内容的视图:

:department_appointments_view

这可能可以作为外连接来完成。我只使用了两个查询和一个联合。

CREATE VIEW `department_appointments_view` AS 
SELECT  da.id                 AS appointment_id,
        dcv.`department_id`   AS department_id, 
        dcv.`department_code` AS department_code, 
    da.`the_date`         AS the_date, 
    da.`time_slot_id`     AS time_slot_id, 
        dcv.start_time        AS start_time,
    da.`attendee`         AS attendee, 
    da.`reason`           AS reason, 
    da.`duration`         AS duration 
FROM 
    `department_appointments` AS da
INNER JOIN department_calendar_view AS dcv
       ON  da.department_id = dcv.department_id
       AND da.the_date = dcv.the_date
       AND da.time_slot_id = dcv.time_slot_id  
UNION   
SELECT 0,
       dcv.department_id,
       dcv.`department_code` , 
       dcv.the_date,
       dcv.time_slot_id,
       dcv.start_time,
       ''    AS attendee,
       ''    AS reason, 
       dcv.`duration`
FROM department_calendar_view AS dcv 
WHERE NOT EXISTS (SELECT 1 
                  FROM  `department_appointments` AS da
                  WHERE  da.department_id = dcv.department_id
                   AND   da.the_date = dcv.the_date
                   AND   da.time_slot_id = dcv.time_slot_id)
ORDER BY department_code, the_date, time_slot_id;

【讨论】:

  • 谢谢@Ryan Vincent,这看起来像是您在这里完成的大量工作。与此同时,我设法与另一个人一起找到了解决方案。我们改变了两个小东西,在这里看看我编辑的帖子:stackoverflow.com/questions/22893385/…
  • 现在我正在与其他问题作斗争,我无法让 edittext 显示来自相应行的数据。这将允许用户保留当前数据或将其更改为其他数据。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 2021-03-25
  • 2020-12-06
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多