c# 字符串转换遇到个问题我要把字符串转换成十六进制插入到SQL表中,该类型为binary;
SqlCommand commm = new SqlCommand("update [user] set data=0x三千多省略了 where account='"+labAcc.Text+"'", conn);
这样是可以的,比如字符串str="32F01023DF也是三千的长度"要把他UPDATE到数据库把我难倒了试了很多转换都不行这个那个的错误都有,请教高手帮帮忙吧 谢谢了
SqlCommand commm = new SqlCommand("update [user] set data=0x三千多省略了 where account='"+labAcc.Text+"'", conn);
这样是可以的,比如字符串str="32F01023DF也是三千的长度"要把他UPDATE到数据库把我难倒了试了很多转换都不行这个那个的错误都有,请教高手帮帮忙吧 谢谢了
{
SqlCommand commm = new SqlCommand("update [user] set data=@data where account='"+labAcc.Text+"'", conn); SqlParameter dataParam = new SqlParameter("data", SqlDbType.Binary); //<---
dataParam.Value = GetBytes("32F01023DF"); //<---
commm.Parameters.Add(dataParam); //<--- conn.Open();
commm.ExecuteNonQuery();
conn.Close();
}byte[] GetBytes(string hexString)
{
byte[] result = new byte[hexString.Length / 2];
for (int i = 0; i < result.Length; i++)
{
result[i] = Convert.ToByte(hexString.Substring(i + i, 2), 16);
}
return result;
}
It would be easier if you have a byte array at the beginning.
string lastName,
string firstName,
string title,
DateTime hireDate,
int reportsTo,
string photoFilePath,
string connectionString)
{
byte[] photo = GetPhoto(photoFilePath); using (SqlConnection connection = new SqlConnection(
connectionString)) SqlCommand command = new SqlCommand(
"INSERT INTO Employees (LastName, FirstName, " +
"Title, HireDate, ReportsTo, Photo) " +
"Values(@LastName, @FirstName, @Title, " +
"@HireDate, @ReportsTo, @Photo)", connection); command.Parameters.Add("@LastName",
SqlDbType.NVarChar, 20).Value = lastName;
command.Parameters.Add("@FirstName",
SqlDbType.NVarChar, 10).Value = firstName;
command.Parameters.Add("@Title",
SqlDbType.NVarChar, 30).Value = title;
command.Parameters.Add("@HireDate",
SqlDbType.DateTime).Value = hireDate;
command.Parameters.Add("@ReportsTo",
SqlDbType.Int).Value = reportsTo; command.Parameters.Add("@Photo",
SqlDbType.Image, photo.Length).Value = photo; connection.Open();
command.ExecuteNonQuery();
}
}public static byte[] GetPhoto(string filePath)
{
FileStream stream = new FileStream(
filePath, FileMode.Open, FileAccess.Read);
BinaryReader reader = new BinaryReader(stream); byte[] photo = reader.ReadBytes((int)stream.Length); reader.Close();
stream.Close(); return photo;
}