简体   繁体   English

在数据库中存储字符串[] []-数组

[英]Storing a string[][]-Array in a database

I would like to store a string[][]-array in a database as datatype "blob". 我想将string [] []-array作为数据类型“ blob”存储在数据库中。 I just found out that I have to convert it, otherwise the data would be practically lost. 我只是发现我必须对其进行转换,否则数据实际上将丢失。 What would be the best way to do that? 最好的方法是什么?

I suppose I should serialize and de-serialize the array, unfortunately I am not quite experienced in that area. 我想我应该对数组进行序列化和反序列化,不幸的是,我在该领域经验不足。 So any help would be appreciated. 所以任何帮助将不胜感激。

PS: I guess I should have said that I need to do that on Android, thus using SQLite. PS:我想我应该说我需要在Android上执行此操作,因此要使用SQLite。 The string[][] has no fixed number of rows or columns. 字符串[] []没有固定数量的行或列。

Why a blob? 为什么是斑点? Why not a clob? 为什么不穿衣服呢? Or better yet, why not a varchar? 还是更好,为什么不使用varchar? Depending on what you're going to do with the data, you should store the data as xml or json in a varchar column. 根据要处理的数据,应将数据以xml或json的形式存储在varchar列中。 It would be searchable too, if necessary. 如有必要,它也是可搜索的。

You didn't say what's in your array but possibly another table would fit the bill, though determining that is far outside the scope of this question (it would make a good new question though). 您没有说数组中有什么,但是可能有另一个表适合您,尽管确定该表已超出此问题的范围(尽管这将成为一个很好的新问题)。

No, far better to serialize your array as text and store it as such. 不,将数组序列化为文本并将其存储为更好。

Edit... A library like JSON-lib supports bi-directional serialization on multidimensional arrays. 编辑...像JSON-lib这样的库支持多维数组上的双向序列化。 Just run your array through JSON-lib to get a JSON string, store that string, then when you want your array back run the string through JSON-lib. 只需通过JSON-lib运行数组以获取JSON字符串,存储该字符串,然后当您想让数组通过JSON-lib重新运行该字符串时即可。

I prefer my text to be in the database as text so I can search for it and view it with one of the many database tools available. 我更喜欢将文本作为文本存储在数据库中,因此我可以使用许多可用的数据库工具之一进行搜索和查看。 I don't want to run code to see what's in a column, and if I need to tweak a value by hand during development I want to be able to update the value, not run a program to do it for me. 我不想运行代码来查看列中的内容,如果在开发过程中需要手动调整值,我希望能够更新该值,而不是运行程序来为我做。

Okay, assuming there won't be nulls. 好吧,假设不会有null。 Write out: 写出:

  • The number of "rows" as a fixed 4-byte value 作为固定4字节值的“行”数
    • For each "row": 对于每个“行”:
    • The number of "columns" as a fixed 4-byte value 作为固定4字节值的“列”数
    • For each string: 对于每个字符串:
      • Convert the string in bytes, eg in UTF-8 ( text.getBytes("UTF-8") ) 以字节为单位转换字符串,例如以UTF-8( text.getBytes("UTF-8")
      • Write out the number of bytes as a fixed 4-byte value 将字节数写为固定的4字节值
      • Write out the data for the string 写出字符串数据

You could just use DataOutputStream 's writeUTF method for the last part, but that would make it slightly harder to read from non-Java platforms. 可以仅在最后一部分中使用DataOutputStreamwriteUTF方法,但这将使从非Java平台读取内容稍难一些。 It depends on your requirements. 这取决于您的要求。 Using DataOutputStream would make it easier to handle in general though. 但是,使用DataOutputStream将使其更易于处理。 For example: 例如:

private static final Charset UTF8 = Charset.forName("UTF-8");

private static byte[] SerializeText(String[][] array)
{
    int rows = array.length;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeInt(rows);
    for (int i = 0; i < rows; i++)
    {
        int columns = array[i].length;
        dos.writeInt(columns);
        for (int j = 0; j < columns; j++)
        {
            byte[] utf8 = array[i][j].getBytes(UTF8);
            dos.writeInt(utf8.length);
            dos.write(utf8, 0, utf8.length);
        }
    }
    dos.flush(); // May not be necessary
    return baos.toByteArray();
}

Instead of XML, I just discovered a JSON library (thanks to this question ), named google gson . 我没有发现XML,而是发现了一个名为google gson的JSON库(由于这个问题 )。

You just have to add the .jar to your classpath, and I give you the code for serialization and deserialization: 您只需要将.jar添加到您的类路径中,我就为您提供用于序列化和反序列化的代码:

import com.google.gson.Gson;

public class JsonTest {

    public static void main(String[] args) {

        String[][] fruits = { { "Banana", "Apple", "Blueberry" }, { "Cherry" }, { "Lemon", "Mango" } };

        Gson gson = new Gson();

        // Serialization
        String json = gson.toJson(fruits);

        // Print: [["Banana","Apple","Blueberry"],["Cherry"],["Lemon","Mango"]]
        System.out.println(json);

        // Deserialization
        String[][] result = gson.fromJson(json, String[][].class);

    }
}

I am really happy that I found this library, XML was too much verbose. 我发现XML这个库太冗长了,我感到非常高兴。

(Sorry for spelling mistakes, I am French.) (很抱歉,我拼写错误,我是法国人。)

You can store it as xml with the xstream library. 您可以使用xstream库将其存储为xml。

It is not very effective due to xml tags, but it works well and it is easy to use: 由于xml标签,它不是很有效,但是效果很好,并且易于使用:

String[][] strs = {
    { "row1_col1", "row1_col2", "row1_col3" },
    { "row2_col1" },
    { "row3_col1", "row3_col2" }
};

XStream xstream = new XStream();
xstream.alias("saa", String[][].class);
xstream.alias("sa", String[].class);
xstream.alias("s", String.class);

String xml = xstream.toXML(str);

System.out.println(xml);

The result: 结果:

<saa>
  <sa>
    <s>row1_col1</s>
    <s>row1_col2</s>
    <s>row1_col3</s>
  </sa>
  <sa>
    <s>row2_col1</s>
  </sa>
  <sa>
    <s>row3_col1</s>
    <s>row3_col2</s>
  </sa>
</saa>

Deserialize: 反序列化:

String[][] strs = (String[][])xstream.fromXML(xml);

I found a solution that works for me. 我找到了适合我的解决方案。

The main problem was that apparently the BLOB has not been saved properly in the database. 主要问题是,显然BLOB尚未正确保存在数据库中。 I used the Android convenience methods to update the database, and now it works even better than I first anticipated. 我使用Android便利方法来更新数据库,现在它的工作甚至比我最初预期的还要好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM