I have a database with images stored in it and I want to replace those images with new ones. Here is the thing: I have a picturebox and in this picturebox I am downloading an image. This image is the one that I want to use to replace the current image of my databaserow where my column "Id" is 6.
Right now I am trying to do it with UPDATE but it is not working and I am wondering why. Here is my code:
private void buttonReplace_Click(object sender, EventArgs e)
{
string sql = "SELECT * FROM [Insert_Image]"; //name of database
SqlDataAdapter dA = new SqlDataAdapter(sql, cn);
DataTable dT = new DataTable();
dA.Fill(dT);
int z = dT.Rows.Count + 1;
int i = 6;
try
{
cn.Open();
byte[] img = null;
FileStream fs = new FileStream(imgLoc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
string strSql = "UPDATE [Insert_Image] SET Picture = " + #img + " WHERE Id LIKE '" + i + "'";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex));
}
finally
{
cn.Close();
}
}
My Problem is that something is saved in my database, but whatever I am saving with this code is not the binary-code for an image. I checked my filestream and that is correct as I am using the same filestream I used for uploading to the picturebox. I would be very glad for any help or ideas.
do not hard code value in the query, instead use.
cmd.Parameters.Addnew SqlParameter("#img", img));
check this cheet sheet on SQL Injection
string strSql = "UPDATE [tablename] SET Picture=#img WHERE Id LIKE '%#i%'";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.Parameters.Add(new SqlParameter("#i", i));
cmd.ExecuteNonQuery();
Related
So I have a table called Bicycle inside BikeStore database on sql server, consists of the following columns:
BID, BName, Description, BType, Brand, Origin, Price, Stock, BImage
Successfully bind all textboxes and one combo box with my data from sql server just by clicking cells on datagridview. Below is the code:
private void dg1_CellClick(object sender, DataGridViewCellEventArgs e)
{
bidTxt.Text = dg1.SelectedRows[0].Cells[0].Value.ToString();
bnameTxt.Text = dg1.SelectedRows[0].Cells[1].Value.ToString();
bdescrichTxt.Text = dg1.SelectedRows[0].Cells[2].Value.ToString();
typeCB.Text = dg1.SelectedRows[0].Cells[3].Value.ToString();
brandTxt.Text = dg1.SelectedRows[0].Cells[4].Value.ToString();
originTxt.Text = dg1.SelectedRows[0].Cells[5].Value.ToString();
priceTxt.Text = dg1.SelectedRows[0].Cells[6].Value.ToString();
stockTxt.Text = dg1.SelectedRows[0].Cells[7].Value.ToString();
But it still generates an error everytime I tried to load the image too. Here's the code:
sqlconn.Open();
SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = " + dg1.SelectedRows[0].Cells[0].Value + "", sqlconn);
da.SelectCommand = cmd;
DataSet ds = new DataSet();
byte[] mydata = new byte[0];
da.Fill(ds, "Bicycle");
DataRow myrow;
myrow = ds.Tables["Bicycle"].Rows[8];
mydata = (byte[])myrow["BImage"];
MemoryStream stream = new MemoryStream(mydata);
BikePic.Image = Image.FromStream(stream);
sqlconn.Close();
}
What did I do wrong?
I'm new at this.
If it just about only retrieving the BLOB on that query then you could do something more simple :
// SqlConnection creation and opening omitted
using(SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = " + dg1.SelectedRows[0].Cells[0].Value + "", sqlconn))
{
byte[] mydata = (byte[])cmd.ExecuteScalar();
MemoryStream stream = new MemoryStream(mydata);
BikePic.Image = Image.FromStream(stream);
}
Also you might want to dispose of stream after creating the Image control but I'm not completely sure.
Problem solved! Add single quotation mark on the SqlCommand line between the blockquote as it'll search up the ID you looking for, like this:
SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = '" + dg1.SelectedRows[0].Cells[0].Value + "'", sqlconn);
Below is the code before modified. See the difference?
SqlCommand cmd = new SqlCommand("SELECT BImage FROM Bicycle WHERE BID = " + dg1.SelectedRows[0].Cells[0].Value + "", sqlconn);
Haha silly me. Thanks anyway guys!
I am storing images to the database in the table test (id, name, image), by reading images from a picture box.
This is my code:
private void browse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "(*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG)|*.BMP;*.JPG;*.GIF;*.JPEG;*.PNG";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
imgloc = openFileDialog1.FileName.ToString();
pictureBox1.ImageLocation = imgloc;
}
}
private void save_Click(object sender, EventArgs e)
{
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
SqlConnection CN = new SqlConnection(constring);
string Query = "insert into test (id,name,image) values('" + txtid.Text + "','" + txtname.Text + "',#img)";
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.ExecuteNonQuery();
CN.Close();
}
It works but I would like to know how to use the update command here.
private void update_Click(object sender, EventArgs e)
{
byte[] img = null;
FileStream fs = new FileStream(imgloc, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
img = br.ReadBytes((int)fs.Length);
SqlConnection CN = new SqlConnection(constring);
// this is a smaple query for update statement and update where id=#id
string Query = "update test set name=#name,image=#img where id=#id ";
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#img", img));
cmd.Parameters.Add(new SqlParameter("#id", txtid.Text));
cmd.Parameters.Add(new SqlParameter("#name", txtname.Text));
cmd.ExecuteNonQuery();
CN.Close();
}
Your code and query should be like this :
SqlConnection CN = new SqlConnection(constring);
string Query = "Update test Set name=#Name,image=#Image where id=#id"
CN.Open();
cmd = new SqlCommand(Query, CN);
cmd.Parameters.Add(new SqlParameter("#Image", img));
cmd.Parameters.Add(new SqlParameter("#Name",txtname.Text));
cmd.Parameters.Add(new SqlParameter("#id",txtid.Text));
cmd.ExecuteNonQuery();
CN.Close();
Just delete that particular record using your Id field and Fire the Save query again, if updating is difficult.
SqlConnection con = Connectionclass.SQLCONNECTION();
SqlDataAdapter da = new SqlDataAdapter();
string query = ("Update Doctor set ID ='" + idtxt.Text + "',Name='" + nametxt.Text + "',Contact='" + contactxt.Text + "',CNIC='" + cnictxt.Text + "',Address='" + addresstxt.Text + "',Qualification='" + qualitxt.Text + "',specialization='" + specialtxt.Text + "',Gender='" + gendertxt.Text + "',DOB='" + dobtxt.Text + "', Fee='"+textBox1.Text+"',Date='" + System.DateTime.Today.ToString("dd-MM-yyyy") + "', Picture= #image where ID='" + idtxt.Text + "'");
da.UpdateCommand = new SqlCommand(query, con);
con.Open();
da.UpdateCommand.Parameters.Add("image", SqlDbType.VarBinary).Value = binaryphoto;
int RowsEffected = da.UpdateCommand.ExecuteNonQuery();
con.Close();
I am importing excel data into sql server using SqlbulkCopy, but the problem is i want to prevent any duplicate records being entered. Is there a way by which duplicate can be ignored or deleted automatically?
protected void Button1_Click(object sender, EventArgs e)
{
string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
string strFileName = FileUpload1.PostedFile.FileName.ToString();
FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);
string excelConnectionString = String.Format(#"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strNewPath + "; Extended Properties=Excel 8.0;");
// Create Connection to Excel Workbook
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
var command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
connection.Open();
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=ARBAAZ-1B14C081;Initial Catalog=abc;Integrated Security=True";
con.Open();
DataTable dt1 = new DataTable();
string s = "select count(*) from ExcelTable";
string r = "";
SqlCommand cmd1 = new SqlCommand(s, con);
try
{
SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
da1.Fill(dt1);
}
catch
{
}
int RecordCount;
RecordCount = Convert.ToInt32(cmd1.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int prv = Convert.ToInt32(r);
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "ExcelTable";
SqlBulkCopyColumnMapping mapping1 = new SqlBulkCopyColumnMapping("excelid", "id");
SqlBulkCopyColumnMapping mapping2 = new SqlBulkCopyColumnMapping("exceldata", "data");
bulkCopy.ColumnMappings.Add(mapping1);
bulkCopy.ColumnMappings.Add(mapping2);
bulkCopy.WriteToServer(dr);
}
con.Open();
DataTable dt = new DataTable();
s = "select count(*) from ExcelTable";
r = "";
SqlCommand cmd = new SqlCommand(s, con);
try
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
catch
{
}
RecordCount = Convert.ToInt32(cmd.ExecuteScalar());
r = RecordCount.ToString();
Label1.Text = r;
con.Close();
int ltr = Convert.ToInt32(r);
if (prv == ltr)
{
Label1.Text = "No records Added";
}
else
{
Label1.Text = "Records Added Successfully !";
}
}
}
}
Can this problem be fixed by creating a trigger to delete duplicates? if yes how? i am a newbie i have never created a trigger.
Another problem is no matter what i try i am unable to get column mapping to work. I am unable to upload data when column names in excel sheet and database are different.
You can create INDEX
CREATE UNIQUE INDEX MyIndex ON ExcelTable(id, data) WITH IGNORE_DUP_KEY
And when you will insert data with bulk to db, all duplicate values will not inserted.
no, either you manage it on your dr object on you code before you load it into the db (like running a DISTINCT operation) or you create a trigger on the DB to check. The trigger will reduce the bulk insert's performace though.
Another option would be to bulk insert into a temp table and then insert into your destination table FROM your temp table using a select DISTINCT
as far as I remember,
you could filter out the redundant rows when importing from the excel file itself.
the following SQL query should be used in the OleDbCommand constructor.
var command = new OleDbCommand("Select DISTINCT ID,Data FROM [Sheet1$]", connection);
I am trying to retrieve image from back end in ASP.Net. Using SQL SERVER 2005 as back end. I have tried n number of codes including the one available online. Can any one guide me solve this issue.
My code is below
Table Design:-
create table Image
(
ImageId Int identity (1,1),ImageName Varchar(50), Image image
)
Code:-
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridData();
}
}
string strcon = "Data Source=SUJITHA\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True";
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//getting length of uploaded file
int length = FileUpload1.PostedFile.ContentLength;
//create a byte array to store the binary image data
byte[] imgbyte = new byte[length];
//store the currently selected file in memeory
HttpPostedFile img = FileUpload1.PostedFile;
//set the binary data
img.InputStream.Read(imgbyte, 0, length);
string imagename =TextBox1.Text;
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Image (ImageName,Image) VALUES (#imagename,#imagedata)", connection);
cmd.Parameters.Add("#imagename", SqlDbType.VarChar, 50).Value = imagename;
cmd.Parameters.Add("#imagedata", SqlDbType.Image).Value = imgbyte;
int count = cmd.ExecuteNonQuery();
connection.Close();
if (count == 1)
{
BindGridData();
TextBox1.Text = string.Empty;
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert('" + imagename + " image inserted successfully')", true);
}
}
}
private void BindGridData()
{
SqlConnection connection = new SqlConnection(strcon);
SqlCommand command = new SqlCommand("SELECT ImageName,Image from [Image]", connection);
SqlDataAdapter daimages = new SqlDataAdapter(command);
DataTable dt = new DataTable();
daimages.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
GridView1.Attributes.Add("bordercolor", "black");
}
SqlConnection con = new SqlConnection(#"Data Source=AMAR-PC\SQLEXPRESS;Initial Catalog=a;User ID=sa;Password=amar");
string path = Server.MapPath("Images/");
if (FileUpload1.HasFile)
{
byte[] img = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile myimage = FileUpload1.PostedFile;
myimage.InputStream.Read(img, 0, FileUpload1.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into images values ('" + TextBox1.Text + "','" + FileUpload1.PostedFile + "')", con);
con.Open();
This is what i did...and I also know that there are many other ways to upload file....
Now I want that a the uploaded pic should be dispayed in Image Control....could you help me now
*/Your code Like this*
**//Insert the file into database**
string strQuery = "insert into tblFiles(Name, ContentType, Data) values (#Name, #ContentType, #Data)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value = "application/vnd.ms-word";
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes;
InsertUpdateData(cmd);
**//Select the file from database**
string strQuery = "select Name, ContentType, Data from tblFiles where id=#id";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = 1;
DataTable dt = GetData(cmd);
if (dt != null)
{
download(dt);
}
private void download (DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch
{
return null;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
Couple of things worry me
you use the master database
your table name is image which is a reserved word in SQL Server
If you need to name tables with reserved names, you need to quote them with square brackets: INSERT INTO [Image] ...
similar questions have been asked and answered many times here
your acceptance rate is 0%
I have done this previously but in a different way. I am trying to get the code below to work. If I do not cast 'OriginalPhoto' or 'Thumbnail' an error occurs. Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query. I don't understand why it asking to cast. However if I do cast it, the images add to the database just fine in a binary data format. When trying to view the images, i get the error 'Unable to display the given data'. I have inserted both byte[] into a table using a SqlDataAdapter and that works. I want to use this method though, what am I doing wrong?
PROFILEGALLERY TABLE CONTAINS:
UserId nvarchar(50)
Title nvarchar(10)
OriginalImage varbinary(max)
ThumbImage varbinary(max)
protected void AddPhotoToDatabase()
{
byte[] OriginalPhoto = GetImage();
byte[] Thumbnail = GenerateThumbnail();
string Title = FileUpload1.FileName.ToString();
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES ('" + User.Identity.Name + "', '" + Title + "', CAST('" + OriginalPhoto + "'AS VARBINARY(MAX)), CAST('" + Thumbnail + "'AS VARBINARY(MAX)))";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
protected byte[] GetImage()
{
byte[] photo = new byte[FileUpload1.PostedFile.ContentLength];
FileUpload1.PostedFile.InputStream.Read(photo, 0, photo.Length);
return photo;
}
protected byte[] GenerateThumbnail()
{
System.Drawing.Image image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
double thumbwidth = 0;
double thumbheight = 0;
double imgsz = 150.0;
if (imgsz / image.Width < imgsz / image.Height)
{
thumbwidth = image.Width * (imgsz / image.Width);
thumbheight = image.Height * (imgsz / image.Width);
}
else
{
thumbwidth = image.Width * (imgsz / image.Height);
thumbheight = image.Height * (imgsz / image.Height);
}
System.Drawing.Image thumb = image.GetThumbnailImage((int)thumbwidth, (int)thumbheight, delegate() { return false; }, (IntPtr)0);
MemoryStream ms = new MemoryStream();
thumb.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
You should use sql parameters:
using( SqlConnection cnn = GetConnection() ) {
using( SqlCommand cmd = cnn.CreateCommand() ) {
cmd.CommandText = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage], [ThumbImage]) VALUES (#UserId, #Title, #OriginalPhoto, #Thumbnail)";
cmd.Parameters.AddWithValue( "#UserId", User.Identity.Name );
cmd.Parameters.AddWithValue( "#Title", Title );
cmd.Parameters.AddWithValue( "#OriginalPhoto", OriginalPhoto );
cmd.Parameters.AddWithValue( "#Thumbnail", Thumbnail );
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
}
}
Don't try to build the data into the insert query. Try this:
string sql = "INSERT INTO [ProfileGallery] ([UserId], [Title], [OriginalImage],
[ThumbImage]) VALUES (#userId, #title, #originalImage, #thumbImage)";
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand comm = new SqlCommand(sql, conn);
comm.Parameters.Add(new SqlParameter("#userId", User.Identity.Name));
comm.Parameters.Add(new SqlParameter("#title", Title));
comm.Parameters.Add(new SqlParameter("#originalImage", OriginalPhoto));
comm.Parameters.Add(new SqlParameter("#thumbImage", Thumbnail));
Just looking at your code, I'm a little concerned that you are wide open for a SQL Injection attack. To help mitigate this should also fix your problem. You need to use a parametized query. Something like
cmd.CommandText="Insert into [ProfileGallery]" +
"(UserId,OriginalPhoto) values (#UserId,#OriginalPhoto)";
cmd.Parameters.AddWithValue("UserId",User.Identity.Name);
cmd.Parameters.AddWithValue("OriginalPhoto",OriginalPhoto);
The reason your code is failing can be seen with this sample application:
static void Main(string[] args)
{
byte[] byteArray = new byte[] { 1, 2, 0 };
Console.WriteLine("This is my byte array: " + byteArray);
Console.ReadLine();
}
This outputs This is my byte array: System.Byte[]
I'm a little shocked that you can add a byte array to a string, especially sicne it just gives us the name of the type.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
string strSQL = "Select * from table6";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
dt.Fill(ds);
grd1.DataSource = ds;
grd1.DataBind();
cn.Close();
}
protected void btn1_Click(object sender, EventArgs e)
{
if(fileupload.HasFile)
{
string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
string ImageName = txt1.Text;
SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
cn.Open();
string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
cn.Close();
BindData();
txt1.Text = "";
}
This simple code is enough to insert images to SQL without taking HTTP Handler
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
SqlConnection cn = new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
string strSQL = "Select * from table6";
SqlDataAdapter dt = new SqlDataAdapter(strSQL, cn);
DataSet ds = new DataSet();
dt.Fill(ds);
grd1.DataSource = ds;
grd1.DataBind();
cn.Close();
}
protected void btn1_Click(object sender, EventArgs e)
{
if(fileupload.HasFile)
{
string imageSrc = "~/Image/" +fileupload.PostedFile.FileName;
string ImageName = txt1.Text;
SqlConnection cn=new SqlConnection("uid=test;pwd=te$t;server=10.10.0.10;database=TestDB");
cn.Open();
string strSql = "Insert Into table6 (ImageName,Image) values ('" + ImageName + "','"+imageSrc+"')";
SqlCommand cmd = new SqlCommand(strSql, cn);
cmd.ExecuteNonQuery();
cn.Close();
BindData();
txt1.Text = "";
}