把二维数组存到数据库的一个字段中

本文介绍如何使用XML序列化及二进制格式处理二维数组的存取操作,通过实例演示了将二维数组转换为XML字符串并保存至数据库的方法,以及如何从数据库中读取XML字符串并还原为原始二维数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

怎样把二维数组存到数据库的一个字段中呢?

又要方便从这个字段中取出来...可以自定义存放格式,例如XML


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
 
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private string m_strXML = "";
 
        // 将二维数组序列化成XML
        private void button1_Click(object sender, EventArgs e)
        {
            string[][] str = { new string[] { "1","2","3" }, new string[] { "A","B","C" } };
            XmlSerializer xml = new XmlSerializer( str.GetType() );
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(ms, Encoding.Default);
            xml.Serialize(writer, str);
 
            // 得到序列化后的XML字符串,可以直接保存到数据库
            m_strXML = Encoding.Default.GetString(ms.ToArray());
            MessageBox.Show(m_strXML);
        }
 
        // 把XML反序列化为二维数组
        private void button2_Click(object sender, EventArgs e)
        {
            // 从数据库取出XML字符串,这里使用m_strXML变量
            XmlSerializer xml = new XmlSerializer( typeof(string[][]) );
            StreamReader sr = new StreamReader(new MemoryStream(System.Text.Encoding.Default.GetBytes(m_strXML)), System.Text.Encoding.Default);
            string[][] str=(string[][])xml.Deserialize(sr);
            foreach (string[] s1 in str)
            {
                foreach (string s2 in s1)
                {
                    MessageBox.Show(s2);
                }
            }
        }     
    }
}
定义的二维数组 string[][] str ,  这个格式,怎么统一呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
 
        private void button1_Click(object sender, EventArgs e)
        {
            string[,] str = new string[,] { { "1""2""ty","9i" }, { "3""7""0" ,"8"}, { "3""7""0","8"} };
 
            BinaryFormatter bFormatter = new BinaryFormatter();
 
            bFormatter.Serialize(ms, str);
             
            // 把ms保存到数据库
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            BinaryFormatter bFormatter = new BinaryFormatter();
            ms.Position = 0;
            string[,] str = (string[,])formater.Deserialize(ms) ;
           // ms.Close();
 
            for (int i = 0; i < str.GetLength(0); i++)
            {
                for (int j = 0; j < str.GetLength(1); j++)
                {
                    MessageBox.Show(str[i,j]);
                }
            }
        }
    }
}



将二维Point类型的数组存储到MySQL数据库中通常需要经过几个步骤: 1. **数据结构映射**: 首先,你需要有一个适合的数据模型来表示Point数组。例如,在Python中可以创建一个名为`Point`的类,包含两个字段如`x`和`y`。然后,你可以将一个二维Point数组封装成列表或列表的列表。 ```python class Point: def __init__(self, x, y): self.x = x self.y = y points_array = [[Point(1, 2), Point(3, 4)], [Point(5, 6), Point(7, 8)]] ``` 2. **连接数据库**: 使用Python的pymysql库或者其他支持的ORM工具(如SQLAlchemy),连接到MySQL服务器。 3. **序列化数据**: 由于MySQL不直接支持存储复杂数据类型,你需要将`Point`对象转换为JSON字符串或者字符串格式,比如逗号分隔值(CSV)格式。 ```python import json # 转换为JSON字符串 json_points = json.dumps(points_array) # 或者转为CSV csv_points = 'Point(x,y),(x,y),...' ``` 4. **插入数据**: 创建一个表来存储这种数据,如果不存在,可以设置为TEXT或BLOB类型来存储大对象。然后通过SQL INSERT命令将序列化的数据插入。 ```python def insert_to_db(): # 假设已有一个名为points_table的表,字段为data_column conn = pymysql.connect(host='localhost', user='your_username', password='your_password') cursor = conn.cursor() # 插入JSON数据 sql = f"INSERT INTO points_table (data_column) VALUES (%s)" cursor.execute(sql, (json_points,)) # 或者插入CSV数据 # sql = f"INSERT INTO points_table (data_column) VALUES ('{csv_points}')" conn.commit() cursor.close() conn.close() insert_to_db() ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值