在项目中,有时可能需要把图片保存入数据库,下面是C#代码示例: 1.需要使用文件流,所以需要引入命令空间:using System.IO; 2.代码如下: //创建文件流,path参数是文件路径 FileStream fs = new FileStream(path, FileMode.Open); int streamLength = (int)fs.Length; //获取文件流的长度。 byte[] image = new byte[streamLength]; //声明字节数组,用于保存图片文件 fs.Read(image, 0, streamLength); //把图片文件转换成为字节数组保存 fs.Close(); //插入Sql语句,@img是Sql语句参数。 string sql = string.Format("insert student values(@img)", image); SqlCommand com = new SqlCommand(sql,con); //con是一个有效的连接对象 //为命令对象添加参数,注意参数的类型 com.Parameters.Add(new SqlParameter("img", SqlDbType.Binary, image.Length, ParameterDirection.Input, true, 0, 0, null, DataRowVersion.Default, image)); con.Open(); com.ExecuteNonQuery(); //执行 con.Close(); 3.需要注意的是,数据库的字段类型是:image