如何在SQL Server中存储和检索varbinary(max)列



我正在开发一个应用程序,我希望将用户的指纹存储到数据库中,然后将其与从设备中获取的指纹进行比较。在将varbinary(max)列转换回字节[]时,我一直有某些问题。我试过使用GetSqlBinary功能,但它给我indexoutofrangeException

我使用下面的代码将模板存储到数据库中,但发现所有用户的值都是相同的。(例如0 x000000)

public int insernewVoter(NSubject thumb) 
{
    connectionOpen();
    byteArray = thumb.GetTemplateBuffer().ToArray();
    int insert = 0;
    cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandText = "INSERT INTO VOTER (THUMB) VALUES(CONVERT(varbinary(max),'" + byteArray + "'))";
    int rowsupdated = cmd.ExecuteNonQuery();
    if (rowsupdated <= 0) {
        MessageBox.Show("Ho Gya");
    }
    else {
        MessageBox.Show("AP MAR KYN NAI JATA :D");
    }
    return 0;
    connectionClose();
}

谁能告诉我如何将字节[]插入varbinary(max)列,然后检索它?

您应该始终使用参数。试试吧:

using(var conn = new SqlConnection("YOUR CONNECTION STRING ..."))
using (var cmd = new SqlCommand("INSERT INTO VOTER (THUMB) VALUES(@THUMB)", conn)) {
    conn.Open();
    var param = new SqlParameter("@THUMB", SqlDbType.Binary) {
        // here goes your binary data (make sure it's correct)
        Value = thumb.GetTemplateBuffer().ToArray()
    };
    cmd.Parameters.Add(param);
    int rowsAffected = cmd.ExecuteNonQuery();
    // do your other magic ...
}

编辑

既然您已经询问了如何检索它,您可以这样做(不确定您的确切需求,但它应该给您一个想法):

private byte[] GetThumbData(int userId) {
    using (var conn = new SqlConnection("YOUR CONNECTION STRING ..."))
    using (var cmd = new SqlCommand("SELECT THUMB FROM VOTER WHERE ID = @ID", conn)) {
        conn.Open();
        cmd.Parameters.AddWithValue("@ID", userId);
        return cmd.ExecuteScalar() as byte[];
    }
}

如果你有文件格式的指纹,那么你可以使用以下代码,WCH将PDF转换为字节,再将字节转换为PDF

  string filepath = Server.MapPath("~/pdf/" + file.FileName);
  byte[] bytes = System.IO.File.ReadAllBytes(filepath);

并将其传递给varbinary的Database字段现在你可以使用

来检索PDF格式的内容
 byte[] pdfcontent =  (byte[])DS.Tables[0].Rows[0]["PDFContent"];

最新更新