C#读写SQL Server数据库图片

时间:2022-08-22 02:58:38

效果图:

C#读写SQL Server数据库图片

下载链接:

http://download.csdn.net/detail/u010312811/9492402

1.创建一个Winform窗体,窗体分为“数据上传”和“数据读取”两部分;

C#读写SQL Server数据库图片

2.在SQL Server数据库中创建一个名为PeopleInformation的数据表,表中分配三个字段,分别为:ID、Name、Photo;

C#读写SQL Server数据库图片

3.将ID字段设置为主键,自增

C#读写SQL Server数据库图片

图片上传的代码:

     //通过数据流读取本地的图片信息
     FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
     byte[] bt = new byte[fs.Length];
     fs.Read(bt, , bt.Length);
     fs.Close();
     //打开数据库的连接
     string strconn = @"Data Source=LONG-PC\;Initial Catalog=PRACTICE;User ID=istrive;Password=istrive";
     SqlConnection conn = new SqlConnection(strconn);
     conn.Open();
     //将信息上传到 SQL Server
     string strcmd = "insert into PeopleInformation (Name,Photo) values (@name,@photo)";
     SqlCommand cmd = new SqlCommand();
     cmd.Connection = conn;
     cmd.CommandText = strcmd;
     cmd.Parameters.Add(new SqlParameter("@name", txtUpload.Text));
     cmd.Parameters.Add(new SqlParameter("@photo",bt));
     cmd.ExecuteNonQuery();
     //关闭数据库连接
     conn.Close();

图片读取的代码:

     //打开数据库连接
     string strcoon = @"Data Source=LONG-PC\;Initial Catalog=PRACTICE;User ID=istrive;Password=istrive ;Connect Timeout=5";
     SqlConnection conn = new SqlConnection(strcoon);
     conn.Open();
     //查询数据库
     string strcmd = "select Name,Photo from  PeopleInformation where Name = @name";
     SqlCommand cmd = new SqlCommand(strcmd, conn);
     cmd.Parameters.Add(new SqlParameter("@name", name));
     SqlDataAdapter adap = new SqlDataAdapter(cmd);
     DataTable dt = new DataTable();
     cmd.ExecuteNonQuery();
     adap.Fill(dt);
     //将图片信息从 DataTable 以数据流的形式读取
     )
     {
         MemoryStream ms = ]["Photo"]);
         picRead.Image = Image.FromStream(ms, true);
     }