我开始我的项目获得Mifare 1k经典卡片的UID - 这非常好用。现在我必须将我的UID放到mySQL数据库中。我将ByteArray转换为字符串 - 这也适用。
private string getcardUID()
{
string cardUID = "";
byte[] receivedUID = new byte[256];
Card.SCARD_IO_REQUEST request = new Card.SCARD_IO_REQUEST();
request.dwProtocol = Card.SCARD_PROTOCOL_T1;
request.cbPciLength = System.Runtime.InteropServices.Marshal.SizeOf(typeof(Card.SCARD_IO_REQUEST));
byte[] sendBytes = new byte[] { 0xFF, 0xCA, 0x00, 0x00, 0x00 };
int outBytes = receivedUID.Length;
int status = Card.SCardTransmit(hCard, ref request, ref sendBytes[0], sendBytes.Length, ref request, ref receivedUID[0], ref outBytes);
if (status != Card.SCARD_S_SUCCESS)
{
cardUID = "Error";
}
else
{
cardUID = BitConverter.ToString(receivedUID.Take(4).ToArray()).Replace("-", string.Empty).ToUpper();
}
return cardUID;
我们知道我无法将最终看起来像0B05C2FD的字符串放到我的数据库中。尝试了不同的数据类型,如INT BIGINT和VARCHAR:
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
connection.Open();
string mycardUID = getcardUID();
int mycardUIDint = Convert.ToInt32(mycardUID, 16);
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO terminal(id,uid,buttoncode,timestamp,transfered,ts)VALUES(@id,@uid,@buttoncode,@timestamp,@transfered,@ts)";
cmd.Parameters.AddWithValue("@id", "");
cmd.Parameters.AddWithValue("@uid", mycardUID);
cmd.Parameters.AddWithValue("@timestamp", DateTime.Now);
cmd.Parameters.AddWithValue("@buttoncode", "1");
cmd.Parameters.AddWithValue("@transfered", "");
cmd.Parameters.AddWithValue("@ts", "");
cmd.ExecuteNonQuery();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
有解决方案吗?我试图转换为Int,但这不可能使用Convert.ToInt32(value,16);输入错误<。<
编辑:已更改的代码已添加Convert.ToInt32
编辑:我找到了一些东西(c# bitconverter.ToString convert to hexadecimal string),但是我不确定我是否能够将它应用到我的程序中,我真的很困惑的是那个问及我对答案更加困惑的人:(< / p>