Insert and Update Image in sql - c#

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();

Related

Update query updates all records except the name

I am stuck with an issue with updating. When I open my Windows form developed in C# using SQL, the update updates all fields but not the name. Could you tell me what I did wrong?
Here is my code
public void cc()
{
cbBname.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from BkhurData";
db.ExeNonQuery(cmd);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbBname.Items.Add(dr["Name"].ToString());
}
}
private void BkhurUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BkhurData set Name='" + tbBpname.Text + "',Details='" + tbBpdetails.Text + "',Price='" + tbBpprice.Text + "',Size='" + tbBpsize.Text + "', Quantity ='"+tbBpquantity.Text+"' where Name = '" + tbBpname.Text + "'";
db.ExeNonQuery(cmd);
tbBpname.Text = "";
tbBpdetails.Text = "";
tbBpprice.Text = "";
tbBpsize.Text = "";
tbBpquantity.Text = "";
cc();
MessageBox.Show("updated successfully");
}
You are updating the Name where the Name equals tbBpname.Text so it will not change the name for row you are updating.
private string originalName;
public void cc()
{
cbBname.Items.Clear();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from BkhurData";
db.ExeNonQuery(cmd);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
cbBname.Items.Add(dr["Name"].ToString());
originalName = dr["Name"].ToString()
}
}
private void BkhurUpdate_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update BkhurData set Name='" + tbBpname.Text + "',Details='" + tbBpdetails.Text + "',Price='" + tbBpprice.Text + "',Size='" + tbBpsize.Text + "', Quantity ='"+tbBpquantity.Text+"' where Name = '" + originalName+ "'";
db.ExeNonQuery(cmd);
tbBpname.Text = "";
tbBpdetails.Text = "";
tbBpprice.Text = "";
tbBpsize.Text = "";
tbBpquantity.Text = "";
cc();
MessageBox.Show("updated successfully");
}
Please note you should use SqlParameters and not build the query as a string.

Is using multiple Sql connection in a button click in c# in asp.net is efficient?

public void buttonclick(object sender,eventArgs e)
{
SqlConnection con0 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con0.Open();
SqlCommand cmd0 = new SqlCommand("", con0);
con0.Close();
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con1.Open();
SqlCommand cmd3 = new SqlCommand("book_master_insert", con1);
cmd3.CommandType = CommandType.StoredProcedure;
SqlParameter customer_id = new SqlParameter("#customer_id", cust_id);
SqlParameter booking_from = new SqlParameter("#booking_from", ddlfrom.SelectedItem.Text);
SqlParameter booking_destination = new SqlParameter("#booking_destination", ddlto.SelectedItem.Text);
SqlParameter load_type = new SqlParameter("#load_type", ddlLoadtype.SelectedItem.Text);
SqlParameter no_of_containers = new SqlParameter("#no_of_containers", txt_no_of_container.Text);
SqlParameter booking_pickupdate = new SqlParameter("#booking_pickupdate", txt_date.Text);
SqlParameter booking_pickuptime = new SqlParameter("#booking_pickuptime", txt_time.Text);
SqlParameter booking_createdate = new SqlParameter("#booking_createdate", localDate);
cmd3.Parameters.Add(customer_id);
cmd3.Parameters.Add(booking_createdate);
cmd3.Parameters.Add(booking_from);
cmd3.Parameters.Add(booking_destination);
cmd3.Parameters.Add(load_type);
cmd3.Parameters.Add(no_of_containers);
cmd3.Parameters.Add(booking_pickupdate);
cmd3.Parameters.Add(booking_pickuptime);
cmd3.ExecuteNonQuery();
con1.Close();
SqlConnection con2 = new SqlConnection(ConfigurationManager.ConnectionStrings["BUM"].ConnectionString);
con2.Open();
SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2);
SqlDataReader rdr = cmd2.ExecuteReader();
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
con2.Close();
}
Because con0, con1, and con2 are the same, you can write it like this, and please make cmd2 like cmd3, using parameterized query:
using (var conn = new SqlConnection("...Connection String..."))
{
conn.Open();
using (var cmd = new SqlCommand())
{
cmd.Connection = conn;
// Query1
cmd.CommandText = "...Query1...";
cmd.ExecuteNonQuery();
// Query2
cmd.CommandText = "...Query2...";
cmd.ExecuteReader();
}
}
Talking about efficiency first what are you trying to do?
System.Data.SqlClient ( ADO.Net ) re-use connection pooling if it detects new connection is same with the first connection made base on it connectionstring.
Calling multiple SqlConnection doesn't matter as long as you close and dispose it after use. Much better if you wrap it with using() {} statement, but keep in mind that it depend on what you are trying to do or what you requirement is. Open/Close of connection is much cheaper than hold open connection for long time. If you can re-use connection do it like what #x... answers.
It is nothing to do with efficiency but you should AVOID appending user input value in you SQL query. This lead to SQL injection and exploitation like what #mar_s said. Alternatively you can use cmd.Parameters.AddWithValue("#Name", "Bob"); for your safety.
Note : I haven't tested the code :
public void buttonclick(object sender,eventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["BUM"].ConnectionString;
using(SqlConnection con0 = new SqlConnection(connectionString))
{
con0.Open();
using(SqlCommand cmd = new SqlCommand("book_master_insert", con0))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#customer_id", cust_id);
cmd.Parameters.AddWithValue("#booking_from", ddlfrom.SelectedItem.Text);
cmd.Parameters.AddWithValue("#booking_destination", ddlto.SelectedItem.Text);
cmd.Parameters.AddWithValue("#load_type", ddlLoadtype.SelectedItem.Text);
cmd.Parameters.AddWithValue("#no_of_containers", txt_no_of_container.Text);
cmd.Parameters.AddWithValue("#booking_pickupdate", txt_date.Text);
cmd.Parameters.AddWithValue("#booking_pickuptime", txt_time.Text);
cmd.Parameters.AddWithValue("#booking_createdate", localDate);
cmd.ExecuteNonQuery();
// This is a BAD idea and you should replace this using parametrized queries
using(SqlCommand cmd2 = new SqlCommand("select booking_ID from booking_master where customer_id='"+cust_id+"' and booking_from='" + ddlfrom.SelectedItem.Text + "'and booking_destination='" + ddlto.SelectedItem.Text + "' and load_type='" + ddlLoadtype.SelectedValue + "' and no_of_containers='" + txt_no_of_container.Text + "' and CAST (booking_pickupdate as date) ='" + txt_date.Text + "' and booking_pickuptime='" + txt_time.Text + "';", con2))
{
using(SqlDataReader rdr = cmd2.ExecuteReader())
{
while (rdr.Read())
{
booking_ID = rdr["booking_ID"].ToString();
}
}
}
}
}
}

MS Access database not updating

Can anybody tell me why my database isn't updating? Here's my code:
protected void editSection_selected(object sender, EventArgs e) {
int index = grdPhone.SelectedIndex;
GridViewRow row = grdPhone.Rows[index+1];
string values = ((DropDownList)sender).SelectedValue;
int tempVal = Convert.ToInt32(values);
int caseage = Convert.ToInt32(keyId);
int value = tempVal;
/*OleDbConnection con = new OleDbConnection(strConnstring);
//string query = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
string query = "Delete HRS_LEVEL_AMOUNT from Categories where parent_id=65 and id=" + caseage;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Dispose();
cmd.Dispose();
con.Close();
accPhoneNumbers.UpdateCommand = "Update Categories set HRS_LEVEL_AMOUNT=" + tempVal + " where parent_id=65 and ID=" + caseage;
*/
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = ? WHERE ID=?";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("HRS_LEVEL_AMOUNT", tempVal);
cmd.Parameters.AddWithValue("ID", caseage);
con.Open();
cmd.ExecuteNonQuery();
}
}
Label1.Text += " editSection Success! (B) " + tempVal;
}
The commented part is my first solution (including the accPhoneNumbers.UpdateCommand).
I really need your help guys.
I hope this can help you:
string str = "UPDATE Categories SET HRS_LEVEL_AMOUNT = #value1 WHERE ID=#value2";
using (OleDbConnection con = new OleDbConnection(strConnstring))
{
using (OleDbCommand cmd = new OleDbCommand(str, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#value1", tempVal);
cmd.Parameters.AddWithValue("#value2", caseage);
con.Open();
cmd.ExecuteNonQuery();
con.close();
}
}
For more information you can visit this video

read access database and bind to label

I am having trouble from binding the data retrieved into the label. which i will create a session variable from the label the data is the supplierid of the recent new record
Here the .cs file
protected void InsertSupplier(object sender, EventArgs e)
{
OleDbConnection mDB = new OleDbConnection();
mDB.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data source="
+ Server.MapPath("~/App_Data/IESDatabase.accdb");
OleDbCommand cmd;
string strSQLInsert = "INSERT INTO "
+ " Supplier (sName, sPhone, sAddress, sCompany, sStatus)"
+ " VALUES (#name, #phone, #add, #co, #status)";
mDB.Open();
cmd = new OleDbCommand(strSQLInsert, mDB);
cmd.Parameters.AddWithValue("#name", txtfullname.Text);
cmd.Parameters.AddWithValue("#phone", Phone.Text);
cmd.Parameters.AddWithValue("#add", txtaddress.Text);
cmd.Parameters.AddWithValue("#co", CompanyNameBox.Text);
cmd.Parameters.AddWithValue("#status", lblStatus.Text);
cmd.ExecuteNonQuery();
mDB.Close();
/*
OleDbDataReader rdr;
string strSQLSelect = "SELECT sSupplierId FROM Supplier ORDER BY sSupplierId";
mDB.Open();
cmd = new OleDbCommand(strSQLSelect, mDB);
rdr = cmd.ExecuteReader();
while (rdr.Read() == true)
{
lblSupplier.Text = rdr["sSupplierId"].ToString();
}
Session["sSupplierId"] = (string)lblSupplier.Text;
*/
MessageBox.Show("Insert New Supplier is successful", "Admin");
Response.Redirect("Adminpage.aspx");
}

Asp.Net Adding Images to SQL Table...What am I doing wrong?

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 = "";
}

Categories

Resources