怎样把二维数组存到数据库的一个字段中呢?
定义的二维数组 string[][] str ,
这个格式,怎么统一呢?
又要方便从这个字段中取出来...可以自定义存放格式,例如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);
}
}
}
}
}
|
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]);
}
}
}
}
}
|