这些天正好学习C#,碰到往数据库中插入GUID,IMAGE类型的数据问题,BAIDU了下,找到了解决方法.
1.GUID
插入数据库时:
string guid=System.Guid.NewGuid().ToString();//或System.Guid.Empty.ToString();
//添加主键
SqlParameter fd = new SqlParameter("@字段名", SqlDbType.UniqueIdentifier, 16);
fd.Value = new Guid(guid);
cmd.Parameters.Add(fd);
从数据库获取时:
using (System.Data.IDataReader reader = cmd.ExecuteReader())
if (reader.Read()){
string id = reader["字段名"];
}
2.img
MemoryStream ms = new MemoryStream();
// 重要!!保存成文件流
pictureBox1.Image.Save("a.bmp");
FileStream fileStream = new FileStream("a.bmp", FileMode.Open, FileAccess.Read);
BinaryReader binaryReader = new BinaryReader(fileStream);
byte[] img = binaryReader.ReadBytes((int)fileStream.Length);
binaryReader.Close();
fileStream.Close();
这个img就是我们需要的
除此之外,还可能需要将图片文件转为Base64格式
例如:
//从pictureBox中获得文件,并保存,这里的格式可自定义
pictureBox1.Image.Save("a.gif");
FileStream fileStream1 = new FileStream("a.gif", FileMode.Open, FileAccess.Read);
byte[] inputBytes1 = new byte[fileStream1.Length];
fileStream1.Read(inputBytes1, 0, System.Convert.ToInt32(fileStream1.Length));
//自定义文件类
TestWork.File file1 = new TestWork.File();
//图片的Guid
file1.FileMainID = guid;
//二进制的图片
file1.Data = inputBytes1;
//二进制数组的长度
file1.Length = inputBytes1.Length;
//调用方法
InsertNormalFileData(file1);
/// <summary>
/// 插入文件
/// </summary>
/// <param name="file">文件对象</param>
/// <param name="databaseName">库名</param>
/// <returns></returns>
private static bool InsertFileData(TestWork.File file, string databaseName)
{
//创建连接对象
SqlConnection con = null;
try
{
//获取连接对象
con = CreateDataBase(databaseName);
//打开连接
con.Open();
//转换格式的converter
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
//创建SqlCommand实例
SqlCommand cmd = con.CreateCommand();
//调用存储过程,察看指定文件是否已经存在
cmd.CommandText = "XXXXXXXX";
//添加主键:File_Main_ID
SqlParameter fileMainID = new SqlParameter("@FILE_MAIN_ID", SqlDbType.UniqueIdentifier, 16);
fileMainID.Value = new Guid(file.FileMainID);
cmd.Parameters.Add(fileMainID);
//声明命令类型为存储过程
cmd.CommandType = CommandType.StoredProcedure;
//获得返回对象
SqlDataReader dr = cmd.ExecuteReader();
//判断文件是否存在
if (dr.Read())
{
//抛出异常
throw new Exception("指定的文件编号已经存在!");
}
//关闭对象
dr.Close();
//创建新实例
//SqlCommand cmd = con.CreateCommand();
//调用Sp插入文件,insert into
cmd.CommandText = "XXXXXXXXXXXXXXX";
cmd.CommandType = CommandType.StoredProcedure;
//创建文件编号对象
//SqlParameter fileMainID = new SqlParameter("@FILE_MAIN_ID", SqlDbType.UniqueIdentifier, 16);
//fileMainID.Value = new Guid(file.FileMainID);
//创建文件内容对象
//第三个参数为文件大小
SqlParameter data = new SqlParameter("@DATA", SqlDbType.Image,file.Data.Length);
//转化二进制为Base64
data.Value = converter.GetBytes(System.Convert.ToBase64String(file.Data));
data.Value = file.Data;
//创建文件大小对象
SqlParameter length = new SqlParameter("@DATA_LENGTH", SqlDbType.Int, 4);
length.Value = file.Length;
//添加参数
//cmd.Parameters.Add(fileMainID);
cmd.Parameters.Add(data);
cmd.Parameters.Add(length);
//执行插入操作
int i = cmd.ExecuteNonQuery();
//返回是否插入成功
return i > 0;
}
catch
{
//抛出异常
throw new Exception("插入文件处理中发生异常");
}
finally
{
if (con != null)
{
//关闭数据库连接
con.Close();
}
}
}
还原图片文件
/// <summary>
/// 获取原始文件
/// </summary>
/// <param name="fileMainID">文件编号</param>
/// <returns>文件实体</returns>
public static TestWork.File GetNormalFileData(string fileMainID)
{
//创建连接对象
SqlConnection con = null;
try
{
//获取连接对象
con = CreateDataBase(fileMainID);
//打开连接
con.Open();
//将Base64转换为二进制
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
//创建SqlCommand实例
SqlCommand cmd = con.CreateCommand();
//调用存储过程,获取文件内容
cmd.CommandText = "XXXXXXXXXXXXXXX";
//添加主键:File_Main_ID
SqlParameter fd = new SqlParameter("@FILE_MAIN_ID", SqlDbType.UniqueIdentifier, 16);
fd.Value = new Guid(fileMainID);
cmd.Parameters.Add(fd);
//声明命令类型为存储过程
cmd.CommandType = CommandType.StoredProcedure;
//执行查询操作,获得返回对象
using (System.Data.IDataReader reader = cmd.ExecuteReader())
//察看是否获得指定File_Main_ID对应的文件
if (reader.Read())
{
//创建文件对象
TestWork.File file = new TestWork.File();
//获取文件编号
file.FileMainID = fileMainID;
System.Text.UnicodeEncoding converter = new System.Text.UnicodeEncoding();
//获取文件内容
string da = converter.GetString((byte[])reader["Data"]);
//转换为二进制,用于判断格式和还原
file.Data = Convert.FromBase64String(da);
//获取文件大小
file.Length = (int)reader["Data_Length"];
//获取图片文件类型
file.FormatType = GetFileImageFormat(file.Data);
//返回文件
return file;
}
//如果没有指定的文件
else
{
//返回null对象
return null;
}
}
catch
{
//抛出异常
throw new Exception("获取原始文件处理中发生异常");
}
finally
{
if (con != null)
{
//关闭数据库连接
con.Close();
}
}
}
//判定图片格式
private static TestWork.ImageFormat GetFileImageFormat(byte[] buffer)
{
//数据有效性检查
if (buffer == null || buffer.Length < 2)
{
return TestWork.ImageFormat.Other;
}
//根据文件头判断
string strFlag = buffer[0].ToString() + buffer[1].ToString();
//察看格式类型
switch (strFlag)
{
//JPG格式
case "255216":
return TestWork.ImageFormat.Jpg;
//GIF格式
case "7173":
return TestWork.ImageFormat.Gif;
//BMP格式
case "6677":
return TestWork.ImageFormat.Bmp;
//PNG格式
case "13780":
return TestWork.ImageFormat.Png;
//其他格式
default:
return TestWork.ImageFormat.Other;
}
}
/// <summary>
/// 文件还原
/// </summary>
/// <param name="file">文件对象</param>
/// <returns></returns>
public void FileRecovery(TestWork.File file)
{
//保存的路径
string path = @"c:\pics\";
string outfile = System.IO.Path.GetDirectoryName(path) + file.FileMainID + "." + file.FormatType;
FileStream fs = new FileStream(outfile, FileMode.OpenOrCreate, FileAccess.Write);
fs.Write(file.Data, 0, file.Data.Length);
fs.Close();
}
自定义文件类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestWork
{
public enum ImageViewType { Normal, Thumbs };
public enum ImageFormat { Other, Jpg, Gif, Png, Bmp };
[Serializable]
//文件对象结构定义
public class File
{
//文件编号
public string FileMainID;
//图片类型格式
public ImageFormat FormatType;
//文件大小
public int Length = -1;
//文件内容
public byte[] Data = null;
}
}