I'm getting an error on inserting image into database.
Given below is the code which I'm trying to inserting an image but couldn't be able to do it correctly.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class welcome : System.Web.UI.Page
{
string fname;
SqlConnection con = new SqlConnection();
string emailname;
protected void Page_Load(object sender, EventArgs e)
{
if ((Session["Username"] == null) && (Session["useraddress"] == null))
{
Response.Redirect("Registration.aspx");
}
else
{
emailname = Session["useremail"].ToString();
Label2.Text = Session["Username"].ToString();
Label3.Text = Session["useraddress"].ToString();
welcomelbl.Text = Session["Username"].ToString();
addlbl.Text = Session["useraddress"].ToString();
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
Session.Clear();
Response.Redirect("login.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
imageupload();
}
The function which I'm using to upload image is given below.
private void imageupload()
{
int imglength = FileUpload2.PostedFile.ContentLength;
byte[] bytearray = new byte[imglength];
fname = FileUpload2.PostedFile.FileName;
TextBox1.Text = fname;
HttpPostedFile image = FileUpload2.PostedFile;
image.InputStream.Read(bytearray, 0, imglength);
SqlConnection con = Connection.conn();
con.Open();
SqlCommand cmd = new SqlCommand("insert into imgtbl (imgname,img,useraddress) values(#name ,#image '" + emailname + "')", con);
cmd.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.AddWithValue("#image", SqlDbType.Image).Value = bytearray;
cmd.ExecuteNonQuery();
con.Close();
}
}
The following is wrong (you're missing a comma between #image and the string that contains emailname):
SqlCommand cmd = new SqlCommand("insert into imgtbl (imgname,img,useraddress) values(#name ,#image '" + emailname + "')", con);
It should be:
SqlCommand cmd = new SqlCommand("insert into imgtbl (imgname,img,useraddress) values(#name ,#image, '" + emailname + "')", con); // Note the missing comma!
Also you started correctly by parameterizing your query, why not the email address? This is user input and thus parameterizing is really a must do to avoid SQL injection.
SqlCommand cmd = new SqlCommand("insert into imgtbl (imgname,img,useraddress) values(#name ,#image, #emailname)", con);
cmd.Parameters.AddWithValue("#name", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.AddWithValue("#image", SqlDbType.Image).Value = bytearray;
cmd.Parameters.AddWithValue("#emailname", SqlDbType.VarChar).Value = emailname;
Another thing: Do you want international users to use your site? Then you should really switch from VARCHAR to NVARCHAR to allow for unicode characters in names.
Please correct you query
SqlCommand cmd = new SqlCommand("insert into imgtbl (imgname,img,useraddress) values(#name ,#image '" + emailname + "')", con);
it should be like this
SqlCommand cmd = new SqlCommand("INSERT INTO imgtbl (imgname, img, useraddress) VALUES (#name, #image, '" + emailname + "')", con);
You missed comma in your query.
When passing data to your SQL server, you should always try to use parameters instead of manually building SQL commands with concatenation.
Instead of:
SqlCommand cmd = new SqlCommand("insert into imgtbl (imgname,img,useraddress) values(#name ,#image '" + emailname + "')", con);
you should parametrize the email name also, like you did with #name and #image:
string sqlCommand = "INSERT INTO imgtbl (imgname, img, useraddress) VALUES (#name, #image, #emailName)";
SqlCommand cmd = new SqlCommand(sqlCommand, con);
cmd.Parameters.AddWithValue("#name", TextBox1.Text);
cmd.Parameters.AddWithValue("#image", bytearray);
cmd.Parameters.AddWithValue("#emailname", emailname);
This will prevent any malformed sql commands to be sent to the database, but most importantly, it will make your calls much more safer. Otherwise you will be exposed to SQL injection attacks!
UPDATE: check out #ThorstenDittmar response, the missing comma is probably causing the syntax error
Related
When I Using this command to insert data, it's totally working..
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
cmd = new OleDbCommand();
cmd.CommandText = "insert into Customer(Customer_Phone,Customer_Name) VALUES('"+tb_CustNum.Text+"','"+tb_CustName.Text+"')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible= true;
}
But, after I add or replace this command, "Syntax error in FROM clause" shows up..
cmd.CommandText = "insert into Transaction(Product_Code,Date,Quantity,Total,Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
This is full code-behind:
public partial class _Default : System.Web.UI.Page
{
OleDbConnection con;
OleDbCommand cmd;
int Quan;
double TotalPrice;
//int i = 0;
string Date = DateTime.Now.ToString("dddd, dd MMMM yyyy");
protected void Page_Load(object sender, EventArgs e)
{
Lb_Date.Text = Date;
}
protected void bt_Calc_Click(object sender, EventArgs e)
{
Quan = Convert.ToInt32(tb_Quan.Text);
TotalPrice = Convert.ToDouble(Lb_Price.Text) * Quan;
Lb_TotalPrice.Text = TotalPrice.ToString();
}
protected void ddl_PizzaCode_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strquery = "SELECT * FROM Product WHERE ID = " + ddl_PizzaCode.SelectedValue;
using (con = new OleDbConnection(#"PROVIDER= Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE =C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
using (cmd = new OleDbCommand(strquery, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(dt);
}
Lb_PizzaName.Text = dt.Rows[0]["Product_Name"].ToString();
Lb_Price.Text = dt.Rows[0]["Price_per_Unit"].ToString();
}
}
protected void btn_Save_Click(object sender, EventArgs e)
{
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
cmd = new OleDbCommand();
cmd.CommandText = "insert into Transaction(Product_Code,Date,Quantity,Total,Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
cmd.CommandText = "insert into Customer(Customer_Phone,Customer_Name) VALUES('"+tb_CustNum.Text+"','"+tb_CustName.Text+"')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible= true;
}
BindUserDetails();
}
protected void BindUserDetails()
{
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();
string strquery = "SELECT * FROM Customer";
string strquery2 = "SELECT * FROM Transaction";
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
using (cmd = new OleDbCommand(strquery, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(ds);
}
using (cmd = new OleDbCommand(strquery2, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(ds2);
}
}
}
}
The word DATE is a keyword in SQL Server, and thus needs to be in square brackets when you are using it as a field name in C#. This line should work:
cmd.CommandText = "insert into Transaction(Product_Code, [Date], Quantity, Total, Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
have you ever heard of SQL-Injection.... you are WIDE OPEN to exposure.
ALL your queries should have data cleaned and parameterized. Never concatenate what you can't control from the web.
Using parameters in your commands basically means using the proper character identifier indicating a parameter. In SQL and Access, you should be good with the "#" sign. Other databases use different parameters. VFP uses "?" as a place-holder, SAP Advantage Database uses ":".
Change your commands (all of them select, insert, update, delete) to something like..
cmd.CommandText =
#"insert into Customer
( Customer_Phone, Customer_Name )
VALUES
( #parmCustomerPhone, #parmCustomerName)";
cmd.Parameters.AddWithValue( "#parmCustomerPhone", tb_CustNum.Text );
cmd.Parameters.AddWithValue( "#parmCustomerName", tb_CustName.Text );
Then you should be good. Concatenation can fail if someone puts in a quote ' as part of a name, such as "O'Mally". The quote would mis-balance your quotes and cause failure.
If your columns are of numeric or date data types, make sure the parameter you are sending is of that type via the AddWithValue() call.
Additionally, for clarification, I am explicitly calling the values in the insert statement as "#parmSomething" so you know it is the parameter value, not the actual column name and avoiding confusion... especially as a beginner for web and querying.
Finally as noted by other. Be careful about reserved words such as date, time, and other sql clauses. These should be qualified or wrapped in brackets such as [Date] or Date
As for your multiple insert statements, SQL typically uses a semi-colon to identify the end of one statement and allow there to be multiple in a single call such as
cmd.CommandText =
#"insert into Transaction
( Product_Code,
[Date],
Quantity,
Total,
Customer_Phone )
values
( #parmPizza,
#parmNow,
#parmQty,
#parmPrice,
#parmPhone );
insert into Customer
( Customer_Phone,
Customer_Name )
VALUES
( #parmCustPhone,
#parmCustName ) ";
// NOW, add all the parameters...
cmd.Parameters.AddWithValue( "#eachParmAbove", respectiveTextDateNumericValue );
...
...
...
THEN execute it. Hopefully the readability of these samples helps you too.
The below is my code to insert gridview data into a database. However, using this I want to check and restrict insertion into the database where records have the same name, location, education and salary. If all of these are the same and those already present in database they should not get inserted. If any one column is different then they should get inserted.
protected void btn_insert_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView1.Rows)
{
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert command", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
UploadStatusLabel.Text = "Records Inserted Successfully";
}
I think hitting the database inside a for loop is a very bad idea when you have other options. I'm not tackling this issue in the below sample.
Your code may be subject to SQL Injection, you need to use parameters to pass your values. If someone filled the input with ";DROP TABLE OpenOfficetext;" and they have DROP permissions, it will be a problem if you're just concatenating strings.
To avoid duplicates, you can check first if a similar record exists.
foreach (GridViewRow g1 in GridView1.Rows)
{
string insertCommand = "insert into OpenOfficetext(Name, Location, Education, Salary) values(#p1, #p2, #p3, #p4)";
string selectCommand = "SELECT COUNT(*) FROM OpenOfficetext WHERE Name = #p1 AND Location = #p2 AND Education = #p3 AND Salary = #p4";
SqlConnection con = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand(selectCommand, con);
con.Open();
cmd.Parameters.AddWithValue("#p1", g1.Cells[0].Text);
cmd.Parameters.AddWithValue("#p2", g1.Cells[1].Text);
cmd.Parameters.AddWithValue("#p3", g1.Cells[2].Text);
cmd.Parameters.AddWithValue("#p4", g1.Cells[3].Text);
if (Convert.ToInt32(cmd.ExecuteScalar()) == 0)
{
cmd.CommandText = insertCommand;
cmd.ExecuteNonQuery();
}
con.Close();
}
please use the below code
if not exist (select * from OpenOfficetext where Name='" + g1.Cells[0].Text + "' and Location='" + g1.Cells[1].Text + "' and Education = '" + g1.Cells[2].Text + "' and Salary = '" + g1.Cells[3].Text + "' )
Begin
SqlConnection con = new SqlConnection(connStr);
cmd = new SqlCommand("insert into OpenOfficetext(Name,Location,Education,Salary) values ('" + g1.Cells[0].Text + "','" + g1.Cells[1].Text + "','" + g1.Cells[2].Text + "','" + g1.Cells[3].Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
End
Not working request. What could be the problem? Before that he wrote through CommandText, all worked well.
Code:
private void buttonSearch_Click(object sender, EventArgs e)
{
string constring = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\HomePC\Desktop\Lab2 DB\Lab2 DB\ResearchDB.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM '"+comboBox1.SelectedItem.ToString()+"' WHERE '"+ comboBox2.SelectedItem.ToString() +"' = '"+ textBox1.Text +"'", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
It'd help if you provided an error, but one obvious issue is that you're not opening the connection.
You can open the connection right after you set the CommandType.
cmd.CommandType = CommandType.Text;
con.Open();
Also, I'd recommend parameterizing your query. It's more secure, and cuts down on potential typos.
using (var cmd = new SqlCommand(
"SELECT * FROM '" + comboBox1.SelectedItem.ToString() + "' WHERE '" + comboBox2.SelectedItem.ToString() + "' = #your_textbox_value", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#your_textbox_value", textBox1.Text);
con.Open();
...
I have a slight problem don't know what it is
I am trying the following query to insert the data from my datagridview to my database
The problem is that when I am executing the query it gives me the following error
Incorrect syntax near ','.
However the data is successfully inserted in the database. I tried to find the answers here but to no avail. Somebody please point out the error.
My code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source HERE");
conn.Open();
int rn = 0;
while (rn < dgvmain.Rows.Count)
{
SqlCommand cmd = new SqlCommand("Insert into mainTab(Token_number,ItemType,Quantity,Amount) values(" + dgvmain.Rows[rn].Cells[0].Value + ",'" + dgvmain.Rows[rn].Cells[1].Value + "'," + dgvmain.Rows[rn].Cells[2].Value + "," + dgvmain.Rows[rn].Cells[3].Value + ")", conn);
cmd.ExecuteNonQuery();
rn++;
}
}
Try something like this:
private void button2_Click(object sender, EventArgs e)
{
// put your SqlConnection into a using block
using (SqlConnection conn = new SqlConnection(#"Data Source HERE"))
{
// define query with parameters
string queryStmt = "INSERT INTO dbo.mainTab(Token_number, ItemType, Quantity, Amount) " +
"VALUES(#TokenNumber, #ItemType, #Quantity, #Amount)";
// put your SqlCommand into a using block
using (SqlCommand cmd = new SqlCommand(queryStmt, conn))
{
// Add parameter definitions to SqlCommand
cmd.Parameters.Add("#TokenNumber", SqlDbType.Int);
cmd.Parameters.Add("#ItemType", SqlDbType.Int);
cmd.Parameters.Add("#Quantity", SqlDbType.Decimal);
cmd.Parameters.Add("#Amount", SqlDbType.Decimal);
int rn = 0;
// now open - as late as possible!
conn.Open();
// iterate
while (rn < dgvmain.Rows.Count)
{
// set parameter values
cmd.Parameters["#TokenNumber"].Value = Convert.ToInt32(dgvmain.Rows[rn].Cells[0].Value);
cmd.Parameters["#ItemType"].Value = Convert.ToInt32(dgvmain.Rows[rn].Cells[1].Value);
cmd.Parameters["#Quantity"].Value = Convert.ToDecimal(dgvmain.Rows[rn].Cells[2].Value);
cmd.Parameters["#Amount"].Value = Convert.ToDecimal(dgvmain.Rows[rn].Cells[3].Value);
// execute INSERT statement
cmd.ExecuteNonQuery();
rn++;
}
conn.Close();
}
}
}
This is so wrong. Please change it like :
while (rn < dgvmain.Rows.Count)
{
SqlCommand cmd = new SqlCommand("Insert into mainTab(Token_number,ItemType,Quantity,Amount) values(#tok,#itm,#qua,#amo)", conn);
cmd.Parameters.AddWithValue("#tok", dgvmain.Rows[rn].Cells[0].Value);
cmd.Parameters.AddWithValue("#itm", dgvmain.Rows[rn].Cells[1].Value);
cmd.Parameters.AddWithValue("#qua", dgvmain.Rows[rn].Cells[2].Value);
cmd.Parameters.AddWithValue("#amo", dgvmain.Rows[rn].Cells[3].Value);
cmd.ExecuteNonQuery();
rn++;
}
I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());