标签:
效果图:
下载链接
1.创建一个Winform窗体,窗体分为“数据上传”和“数据读取”两部分;
2.在SQL Server数据库中创建一个名为PeopleInformation的数据表,表中分配三个字段,分别为:ID、Name、Photo。
3.将ID字段设置为主键,自增
图片上传的代码
1 //通过数据流读取本地的图片信息
2 FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
3 byte[] bt = new byte[fs.Length];
4 fs.Read(bt, 0, bt.Length);
5 fs.Close();
6 //打开数据库的连接
7 string strconn = @"Data Source=LONG-PC\;Initial Catalog=PRACTICE;User ID=istrive;Password=istrive";
8 SqlConnection conn = new SqlConnection(strconn);
9 conn.Open();
10 //将信息上传到 SQL Server
11 string strcmd = "insert into PeopleInformation (Name,Photo) values (@name,@photo)";
12 SqlCommand cmd = new SqlCommand();
13 cmd.Connection = conn;
14 cmd.CommandText = strcmd;
15 cmd.Parameters.Add(new SqlParameter("@name", txtUpload.Text));
16 cmd.Parameters.Add(new SqlParameter("@photo",bt));
17 cmd.ExecuteNonQuery();
18 //关闭数据库连接
19 conn.Close();
图片读取的代码:
1 //打开数据库连接
2 string strcoon = @"Data Source=LONG-PC\;Initial Catalog=PRACTICE;User ID=istrive;Password=istrive ;Connect Timeout=5";
3 SqlConnection conn = new SqlConnection(strcoon);
4 conn.Open();
5 //查询数据库
6 string strcmd = "select Name,Photo from PeopleInformation where Name = @name";
7 SqlCommand cmd = new SqlCommand(strcmd, conn);
8 cmd.Parameters.Add(new SqlParameter("@name", name));
9 SqlDataAdapter adap = new SqlDataAdapter(cmd);
10 DataTable dt = new DataTable();
11 cmd.ExecuteNonQuery();
12 adap.Fill(dt);
13 //将图片信息从 DataTable 以数据流的形式读取
14 if (dt.Rows.Count != 0)
15 {
16 MemoryStream ms = new MemoryStream((byte[])dt.Rows[0]["Photo"]);
17 picRead.Image = Image.FromStream(ms, true);
18 }
标签:
原文地址:http://www.cnblogs.com/imstrive/p/5396036.html