Info repeatedly getting recorded in DB - c#

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

Related

Syntax error in FROM clause in OleDbCommand

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.

C# Insert Into syntax error

I am trying to insert data into a table in MS Access. I keep getting the error Missing semicolon (;) at end of SQL statement. or a different error saying that i my Insert query needs to have a value or table in it. Here is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace MiddleWare
{
public partial class Sales : Form
{
public Sales()
{
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
int empId = int.Parse(txtEmpID.Text);
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper])
VALUES (#Printers,#Ink,#Paper)
SELECT #EmpID FROM (Emplopyee)";
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd.Parameters.AddWithValue("#Printers", OleDbType.VarWChar).Value = txtPrinters.Text;
cmd.Parameters.AddWithValue("#Ink", OleDbType.VarWChar).Value = txtInk.Text;
cmd.Parameters.AddWithValue("#Paper", OleDbType.VarWChar).Value = txtPaper.Text;
cmd.Parameters.AddWithValue("#EmpID", OleDbType.VarWChar).Value = txtEmpID.Text;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text);
cmd.CommandText = "SELECT [Total Sales] FROM Sales WHERE EmpID=#EmpID";
string result = cmd.ExecuteScalar().ToString();
MessageBox.Show(result);
}
}
private void Sales_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'DataSet1.DataTable1' table. You can move, or remove it, as needed.
this.DataTable1TableAdapter.Fill(this.DataSet1.DataTable1);
}
private void btnReport_Click(object sender, EventArgs e)
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb");
{
this.DataTable1TableAdapter.Fill(this.DataSet1.DataTable1);
this.reportViewer1.RefreshReport();
}
}
}
}
You should seperate the queries by semicolon
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper])
VALUES (#Printers,#Ink,#Paper);
SELECT #EmpID FROM (Emplopyee)";
Also you can't pass the column name as parameter. In that case use dynamic query.
you should change the query to this:
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper], [EmpID])
VALUES (#Printers,#Ink,#Paper,
SELECT EmpID FROM (Employee) )";
It most likely should read:
string cmdText = #"INSERT INTO [Sales]
([Printers], [Ink], [Paper], [EmpID])
VALUES (#Printers, #Ink, #Paper, #EmpID)";
The "cmd.Paramter.AddWithValue" are unnecessary.
Try formatting your cmdText as
cmd = "INSERT INTO [Sales] ([Printers], [Ink], [Paper])
VALUES (" + txtPrinters.Text + " ," + txtInk.Text + ", " + txtPaper.Text + ")
This clears up confusion of "cmd.Paramter.AddWithValue" duplicating or overriding values.
Rewritten btnUpdate_Click (also not sure if Emplopyee is a typo or not)
private void btnUpdate_Click(object sender, EventArgs e)
{
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\\cp-stud-nas1\users\mat72462\Documents\SalesData.accdb"))
using (OleDbCommand cmd = new OleDbCommand(cmdText, con))
{
con.Open();
cmd = "INSERT INTO [Sales] ([Printers], [Ink], [Paper]) VALUES (" + txtPrinters.Text + " ," + txtInk.Text + ", " + txtPaper.Text + ") SELECT " + textEmpID.Text + " FROM (Emplopyee)";
cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT [Total Sales] FROM Sales WHERE EmpID=#EmpID";
string result = cmd.ExecuteScalar().ToString();
MessageBox.Show(result);
}
}

C# sql related exception [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to do a simple C# windows application as a beginner. But I get a System.Data.SqlClient.SqlException. When I try to connect to database it says connection is OK. But it doesn't allow me to create any tables using visual studio. I can't figure out why it doesn't show options to add new table.
Here is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace best
{
public partial class Form1 : Form
{
SqlConnection con=new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Janith Kularathne\Documents\testing.mdf;
Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void insertB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into details values('"+ idBox.Text +"', '"+ nameBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text="";
DisplayDetails();
MessageBox.Show("Insertion succesfull");
}
private void deleteB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from details where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text = "";
DisplayDetails();
MessageBox.Show("delete succesfull");
}
private void updateB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update details set id, name,category where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text = "";
DisplayDetails();
MessageBox.Show("Update succesfull");
}
private void searchB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "selet *from details where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
DisplayDetails();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
DisplayDetails();
}
public void DisplayDetails()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from details";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
}
Your code currently contains a variety of different issues, which I'll elaborate a bit on and should resolve some of your current problems :
Unnecessary closing parentheses
Typos and Misspellings
Incorrect Syntax
Using Parameterization
In addition to these, I'd highly recommend reading through some tutorials on using the different methods like ExecuteNonQuery(), ExecuteReader() and ExecuteNonScalar() to determine how to actual retrieve values from your queries once you execute them.
Unnecessary Closing Parentheses
You currently have a trailing closing parentheses within each of your queries which is likely causing a syntax error within your SELECT, UPDATE, and DELETE queries :
// Notice the unnecessary trailing ')', which should only be useful within your INSERT call
cmd.CommandText = "..." + idBox.Text + "')";
Typos and Misspellings
An additional typo is present within your search query as well as the word "SELECT" is misspelled:
// "selet" should be "Select"
cmd.CommandText = "selet *from details where id= '" + idBox.Text + "')";
Incorrect Syntax
Your current UPDATE query doesn't actually appear to be doing anything. You are using the SET keyword, but aren't actually setting the values to anything :
// UPDATE queries should be in the form UPDATE {table} SET {Column} = {Value} WHERE ...
cmd.CommandText = "update details set id, name,category where id= '" + idBox.Text + "')";
Parameterization, Not Concatenation
Additionally, you should really consider using parameterization when building your queries. It can help avoid nastiness like SQL Injection and prevent syntax errors as well.
You can see an example of what this might look like for one of your methods below :
private void searchB_Click(object sender, EventArgs e)
{
con.Open();
var query = "SELECT * FROM details WHERE ID = #id";
using(var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#id",idBox.Text);
using(var reader = cmd.ExecuteReader())
{
// Access your results here and do something with them
}
}
}

SqlCommand connection string for localhost database

I am trying to create a simple website in VS Express for Web 2013 which can interact with a database "Parts." My database is stored in the app_data folder. I am able to view the connection in the Server Explorer, which implies the connection string is saved. However, the following code throws 2 errors:
Error 13 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments
Error 14 Argument 2: cannot convert from 'string' to 'System.Data.SqlClient.SqlConnection'
I don't know how to remedy this. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')", connstring);
cmd.ExecuteNonQuery();
}
}
I'm completely new to c#, so please keep that in mind. Thanks for your help.
UPDATE: The following code throws two errors, both of which are:
Error 15 The name 'conn' does not exist in the current context
I'm new to c#, but it doesn't look like there's anything wrong with the code. The name "conn" is clearly defined right above.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
using (var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, #quantity, #category)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
cmd.Parameters.AddWithValue("quantity", quantityBox.Text);
cmd.Parameters.AddWithValue("category", categoryList.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
using(var conn = new SqlConnection(connectionString))
{
conn.Open();
// use conn to create the command
}
But important: YOUR SQL IS REALLY REALLY DANGEROUS. That is open to SQL injection, a HUGE and trivially easy attack surface. Please please parameterize that.
For example:
using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, ...)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
//...
conn.Open();
cmd.ExecuteNonQuery();
}
(note you need to add a few yourself; I have left it incomplete, just name and description used for example)
What is connect value from your config?
Can you try
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
and now issue the query.
You need to create a SqlConnection first:
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')"
, conn);
cmd.ExecuteNonQuery();
Some early habits to get into:
Do not concatenate SQL strings. This is for several reasons, not the least of which is the vulnerability to SQL Injection attacks.
wrap your connection and command in using statements. That ensures that the connections are closed properly if there is an exception.
The end result will look something like:
string connstring = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connstring))
{
string sql = "INSERT INTO PARTS VALUES(#name, #description, #quantity, #categoryList)"
using(SqlCommand cmd = new SqlCommand(sql , conn))
{
cmd.Parameters.AddWithValue("#name", nameBox.Text);
... etc.
cmd.ExecuteNonQuery();
}
}

Getting error on inserting image into database

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

Categories