Click here to Skip to main content
15,889,315 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I Prepared a hex string from the Byte array and using it in the query for concatenation. a hex string will look like 0x123456789ABCDEF
C#
hexStr = "0x1234FFCD5";
sql = "Insert into MembersTable
(col1,col2,col3,col4)"
         + "VALUES('" + _GUID + "','" + _Name + "','" + _Pass + "','"
+ hexStr + "');";

will this process will work
am getting error like
Implicit conversion from data type varchar to binary is not allowed. Use the CONVERT function to run this query
Posted
Updated 25-Aug-17 1:36am
v4

Instead of concatenating the values into your SQL statement, use SqlParameter[^].

The statement could look something like:
C#
sql = "Insert into MembersTable
(col1,col2,col3,col4)"
         + "VALUES(@guid,@name,@pass,@hexstr);";



Now if you define the parameter @hexstr to type binary (see: http://msdn.microsoft.com/en-us/library/system.data.sqldbtype.aspx[^]) you can assign a proper binary value to the parameter and you don't have to convert it at database side.

Also consider using varbinary instead of binary if the length of the binary data varies a lot.
 
Share this answer
 
Parameterizing the query can solve this problem
C#
hexStr = "0x1234FFCD5";
sql = "Insert into MembersTable(col1,col2,col3,col4) VALUES(@guid, @name, @pass, @hex);";

SqlCommand insertCmd=new SqlCommand(sql, conn); /*Assuming conn is an open SqlConnection*/

insertCmd.Parameters.Add("@guid",_GUID);
insertCmd.Parameters.Add("@name",_Name);
insertCmd.Parameters.Add("@pass",_Pass);
insertCmd.Parameters.Add("@hex",hexStr); 

insetCmd.ExecuteNonQuery();

If problem persists, please provide the full code.
 
Share this answer
 
Comments
pradeep manne 4-Jan-12 4:53am    
hi,
i have to insert hex values into runtime created Temp table
convert your file into byte

Byte[] Attimg;
using (FileStream fs = new FileStream(fileURL, FileMode.Open))
{
BinaryReader reader = new BinaryReader(fs);

Attimg = reader.ReadBytes((int)fs.Length);

fs.Close();
}

and then save it into database..

qry=insert into table (c1,c2,c3) values ('"+c1+"','"+c2+"',@c3);

cmd=new sqlcommand(qry,con);

cmd.parameter.addwithvalue(@c3,sqldbtype.binary).value=Attimg;

con.open();
cmd.executenonquery();
con.close();
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900