Save a picture into database without binding source - c#

I tried to save a picture into database using Sqlcommand . When I save , there is an exception throw said " Implicit conversion from data type varchar to varbinary(max) is not allowed. Use the CONVERT function to run this query."
here is the code:
private void btn_save_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
SqlCommand cmd1= new SqlCommand();
SqlCommand cmd2 = new SqlCommand();
string squ1;
squ1 = "INSERT INTO Customer (cus_name, cus_address, cus_Image)Values('" + textBox1.Text + "' , '" + textBox2.Text + "', '"+pictureBox1 .Image +"');";
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
cmd1.Connection = con;
cmd1.CommandText = squ1;
cmd1.ExecuteNonQuery();
con.Close ();
}
// the browser button to get a picture
private void btn_browseImage_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog () == DialogResult .OK )
{
pictureBox1.ImageLocation = f.FileName;
}

You have to pass the image data as a varbinary parameter to the query:
using (var con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\ProgramData\MyDB\TestingDB.mdf;Integrated Security=True;Connect Timeout=30"))
using (var cmd1 = new SqlCommand("INSERT INTO Customer (cus_name, cus_address, cus_Image)Values(#name, #address, #image);", con))
{
var imageData = new MemoryStream();
pictureBox1.Image.Save(imageData, pictureBox1.Image.RawFormat);
cmd1.Parameters.AddWithValue("#name", textBox1.Text);
cmd1.Parameters.AddWithValue("#address", textBox2.Text);
cmd1.Parameters.Add("#image", SqlDbType.VarBinary).Value = imageData.ToArray();
con.Open();
var result = cmd1.ExecuteNonQuery();
}
And you should really read up on how to use SqlCommand to avoid future SQL injection.

The statement '"+pictureBox1.Image +"' will actually call pictureBox1.Image.ToString() which is not the binary content of the image. Use SqlParameters to add your binary data. You can find a solution here...

Related

updating sql server database using c# in asp.net

There isn't any compile error but the database doesn't get updated at all. what is wrong with the code?
protected void Page_Load(object sender, EventArgs e) {
rno.Text = Request.QueryString["rno"];//rno is a textbox
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "select fname from table1 where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
SqlDataReader reader = command.ExecuteReader();
if (reader.Read()) {
fname.Text = reader["xcountry"].ToString().Trim(); //fname is a textbox
}
reader.Close();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
protected void modify_Click(object sender, EventArgs e) {
fName.ReadOnly = false;
}
protected void savechanges_Click(object sender, EventArgs e) {
string connectionString = #"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = db1; Integrated Security = True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update table1 set fname=#fname where rno = #rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", sfname);
command.Parameters.AddWithValue("#rno", rno.Text.Trim());
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
fName.ReadOnly = true;
}
I have tried your code which executed fine and updated database table as well.
I have tried like below :
string connectionString = #"data source=MS-KIRON-01;initial catalog=TestDatabase;integrated security=True;MultipleActiveResultSets=True";
SqlConnection cnn = new SqlConnection(connectionString);
cnn.Open();
String sql = "update TestTable set fname=#fname where rno =rno";
SqlCommand command = new SqlCommand(sql, cnn);
command.Parameters.AddWithValue("#fname", "Test");
command.Parameters.AddWithValue("#rno", "rno");
command.ExecuteNonQuery();
command.Dispose();
cnn.Close();
Another way I have tried.
using (SqlConnection connection = new SqlConnection(connectionString ))
{
connection.Open();
var queryText = "UPDATE TestTable SET fname = '" + requestPram.fname + "' WHERE rno ='" + requestPram.rno + "'";
using (SqlCommand cmd = new SqlCommand(queryText, connection))
{
responseResults = await cmd.ExecuteNonQueryAsync();
}
connection.Close();
}
Hope it would help
After searching for a while, I found out that this code was executing perfectly. The only problem was that everything was inside the page_Load() method and thus the page was reloading everytime I updated the database and thus removing the small window to edit the textboxes. The appropriate solution was to associate this code with some button event rather than with the page_Load() event.

C# and Access database doesn't insert/save my data

I wrote an application with C# and MS Access. I have my form login which it works. OK. And I have an insert statement which does not throw any error, but everything I enter into my textbox doesn't get inserted into my database, and when I want to make an update, it returns the same as insert statement, I mean no error, but the row is not inserted or updated.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void validateaddmember_button_Click(object sender, EventArgs e)
{
addmember.Visible = false;
MemoryStream ms = new MemoryStream();
pictureBox4.Image.Save(ms, pictureBox4.Image.RawFormat);
byte[] a = ms.GetBuffer();
ms.Close();
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],[Password],[Function],[Role],[Registerdata],[Personaldescription],[Phonenumber],[Picture]) VALUES(#f,#l,#e,#p,#fu,#r,#reg,#per,#ph,#pic) ";
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
cmd.Parameters.AddWithValue("#l", lastname_textbox.Text);
cmd.Parameters.AddWithValue("#e", email_textbox.Text);
cmd.Parameters.AddWithValue("#ph", phone_textbox.Text);
cmd.Parameters.AddWithValue("#fu", function_textbox.Text);
cmd.Parameters.AddWithValue("#r", role_dropbox.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#per", richTextBox1.Text);
cmd.Parameters.AddWithValue("#p", repeatpassword_textbox.Text);
cmd.Parameters.AddWithValue("#pic", a);
cmd.ExecuteNonQuery();
con.Close();
}
And here I have in other form my update.
string stringcon = System.Configuration.ConfigurationManager.ConnectionStrings["rent"].ConnectionString;
private void bunifuFlatButton1_Click(object sender, EventArgs e)//login method
{
OleDbConnection con = new OleDbConnection(stringcon);
OleDbCommand cmd2 = new OleDbCommand();
cmd2.Parameters.Clear();
cmd2.Connection = con;
cmd2.CommandText ="update [team] set [Numberoflogin] = [Numberoflogin] + 1 where [Email]=#LEMAIL";
cmd2.Parameters.AddWithValue("#LEMAIL", materialSingleLineTextField1.Text);
con.Open();
cmd2.ExecuteNonQuery();
con.Close();
}
Along with marc_s's important note -- you switched phone and password, make sure you fix that -- you only need # in the sql string. So not
cmd.Parameters.AddWithValue("#f", firstname_textbox.Text);
but
cmd.Parameters.AddWithValue("Firstname", firstname_textbox.Text);
Use the field name (Firstname). #f is just a marker. With Access, you could write the sql string like so:
cmd.CommandText = "INSERT INTO [team]([Firstname],[Lastname],[Email],
[Password],[Function],[Role],[Registerdata],[Personaldescription],
[Phonenumber],[Picture]) VALUES(?,?,?,?,?,?,?,?,?,?)";
so when you add the parameter value, use the field name.
You could also open the connection right before cmd.ExecuteNonQuery();, like your update form.

Emp timeout time not saving in database

I am making emp time attendance register. I am using below code .. here insert query working fine and time-in successfully save in database timein field. Update query also execute successfully but databasae not updated...anyone please help for this...
private void checkin_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "insert into timeatten (id,name,timein)values('" +comboBox1.Text+"','"+textBox1.Text+"','"+textBox2.Text+"' )";
comm.Connection = conn;
comm.ExecuteNonQuery();
MessageBox.Show("Successfully check in");
conn.close();
}
private void checkout_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source.............");
conn.Open();
SqlCommand comm = new SqlCommand();
comm.CommandText = "update timeatten set timeout='" + textBox2.Text + "' where id='" + comboBox1.Text +"'";
MessageBox.Show("Successfully Checkout");
conn.close();
}
I think you're missing these two lines in checkout_Click:
comm.Connection = conn;
comm.ExecuteNonQuery();

What is the optimal / standard method of using a sql connection?

protected void populateDataGrid()
{
string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
string command = "select * from student";
SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString);
DataSet data = new DataSet();
dataAdapter.Fill(data);
GridView1.DataSource = data;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (studentID, studentFirstName, studentLastName)
VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')";
SqlConnection sqlConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
The first function gets all the table data and dumps it to a gridview.
The second function takes input and inserts it into the database.
How can these functions be condensed or simplified?
How can these functions be condensed or simplified?
I would focus on correctness before simplification. Currently I can see at least two problems with the code:
You should absolutely use parameterized SQL instead of putting the values into the SQL itself. Your current code is prone to SQL injection attacks.
You should use using statements so that connection and command are both closed automatically even if exceptions are thrown.
Then in terms of simplification:
You can use the SqlCommand constructor which takes the text and connection - the type defaults to Text anyway.
I would personally try to separate the UI code from the storage code, at least for a non-trivial project. You should look at ASP.NET MVC, at least to get some idea of separation, even if you don't change to start using it.
In Button2_Click(object sender, EventArgs e) method , you need to use parametrized query to avoid SQL Injection.
That is the standard way.
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString;
string command = #"INSERT INTO [student] (
studentID, studentFirstName, studentLastName
) VALUES (
#studID, #FName, #LName
)";
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = command;
cmd.Parameters.AddWithValue("#studID", TextID.Text);
cmd.Parameters.AddWithValue("#FName", TextFirstName.Text);
cmd.Parameters.AddWithValue("#LName", TextLastName.Text);
cmd.Connection = sqlConnection;
sqlConnection.Open();
cmd.ExecuteNonQuery();
sqlConnection.Close();
}
TextID.Text = "";
TextFirstName.Text = "";
TextLastName.Text = "";
populateDataGrid();
}
Hope Its Helpful.

Fetching data from SQL Server 2005 using c#

I would like to retrieve a particular column from a table when the values from two other columns are equal. My code is as follows. The four columns are id,destination,source,price.
I want to display the price when the destination and source are equal.
Could you please help me?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true");
con.Open();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = new SqlCommand("select price from metro where source='" + textBox1.Text + "' and destination='" + textBox2.Text + "'", con);
da.Fill(dt);
for(int i=0;i<dt.Rows.Count;i++)
{
textBox3.Text = dt.Rows[0][3].Count.ToString();
}
}
I thing you are after this ....
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data source=.;initial catalog=loki;integrated security=true"))
{
string query = "select price from metro where source= #Source and destination = #Destination";
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#Source", textBox1.Text);
cmd.Parameters.AddWithValue("#Destination", textBox2.Text);
con.Open();
object o = cmd.ExecuteScalar();
if(o != null && o != DBNull.Value)
{
string price = (string) o; //please cast the return type as required
textBox3.Text = price;
}
con.Close();
}
}
}

Categories

Resources