Greeting All
I'm trying to create an asp.net webpage using C# to Upload a details about products containing Product name, description, image and Product Number.
protected void btnSubmit_Click(object sender, EventArgs e)
{
string path = Server.MapPath("ProductsImages/");
if (FileUpload1.HasFile)
{
string ext = Path.GetExtension(FileUpload1.FileName);
if (ext == ".jpg" || ext == ".png")
{
FileUpload1.SaveAs(path + FileUpload1.FileName);
string name = "~/ProductsImages/" + FileUpload1.FileName;
string s = " insert into Products values('" + txtProductName.Text.Trim() + txtDescription.Text.Trim() + txtPrice.Text.Trim() + txtProductNumber.Text.Trim() + "','" + name + "')";
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Write("Your File Has Been Uploaded");
}
else
{
Response.Write("You can upload only Jpg and png file");
}
}
else
{
Response.Write("Please Select an file To upload");
}
}
but when I start debugging it shows me an error : SqlException :
column name or number of supplied values does not match table definition.
However, my database design :
Column Name | Data type
Name nvarchar(50)
Description nvarchar(50)
Price nvarchar(50)
Image image
Product_Number nvarchar(50)
I don't know where is the wrong, in code or database??
Put a breakpoint on the line that you are creating your SQL Command. When the breakpoint is hit, inspect the value of the variable s. Your problem will become apparent: all you're doing is concatenating several of your fields into one single string. If you split them correctly, it should work.
On the other hand, you shouldn't be building your queries like that anyway. Use SqlParameters to correctly build and escape your queries.
Your insert query is missing commas.
It should be:
string s = " insert into Products values('" + txtProductName.Text.Trim() + "', '" + txtDescription.Text.Trim() + "', " + txtPrice.Text.Trim() + ", " + txtProductNumber.Text.Trim())";
It would be better to do it with SqlParameters, though. Here's how I'd do it:
var queryInsert = "Insert Into Products Values (#productName, #productDescription, #productPrice, #productNumber)";
cmd.Parameters.AddWithValue("#productName", txtProductName.Text.Trim());
cmd.Parameters.AddWithValue("#productDescription", txtDescription.Text.Trim());
...you get the idea. You'd set up the parameters for each of them like I did above.
Related
What i intend to do is to insert the value into SQL database table. Firstly, let me explain the flow. I generate dynamic textboxes on the Form. Next, while inserting all the values from other textboxes and comboboxes i do no have any problem. But to get all the values entered manually from dynamically created textboxes was a challenge for me. Which i managed to fix it using the following code.
foreach (TextBox textbox in this.panel1.Controls.OfType<TextBox>())
{
string message_0 = "";
message_0 = textbox.Text.ToString();
}
But when i insert the values into the database using the insert query i face a problem into database. The value gets inserted with the duplication of other columns too if i place the for loops curly braces after the sql commands.
foreach (TextBox textbox in this.panel1.Controls.OfType<TextBox>())
{
string message_0 = "";
message_0 = textbox.Text.ToString();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
string a = "insert into new_product (name, description, image, fk_type, date, reference, field_value) values ('" + textBox3.Text + "', '" + richTextBox1.Text + "' ,#images ,'" + comboBox1.SelectedValue.ToString() + "', '" + dateTimePicker1.Value.ToString("dd-mm-yy") + "','" + textBox1.Text + "', '" + message_0 + "') ";
cmd.CommandText = a;
cmd.Parameters.Add(new SqlParameter("#images", images));
cmd.ExecuteNonQuery();
table_update();
}
Is it normal in this case or am i doing anything wrong here. Any help would be appreciated guys. Thank you.
enter image description here
I have an c# program that update 2 columns, in each table in my access database file(.mdb). Columns that I'm updatnig are short string type, I am also changing their size to 255, before updating. I have 15 files, my code is working for first 7 dbs, and crash on 8-th file. I am updating each code separately, and it crash about in the middle of database
System.Data.OleDb.OleDbException: 'Record is too large.'
Query string that is crashing :
UPDATE CARTE SET SYMBOLE = 'AGLX19.A8E', SYMBOLE2 = 'AWLX19.A8E;#P516.#PQ;#P517.#PQ;#P518.#PQ;#P519.#PQ' WHERE CODE = '2862411';
private void UpdateSYMBOLEinDatabase(string tableName, string code)
{
if (symboleMdb[0] == "")
return;
string queryString = "UPDATE " + tableName +
" SET SYMBOLE = '" + symboleMdb[0] + "', SYMBOLE2 = '" + symboleMdb[1] + "' " +
"WHERE CODE = '" + code + "';";
if (symboleMdb[1] == "")
queryString = queryString.Replace(", SYMBOLE2 = ''", "");
using (OleDbConnection connectionInput = new OleDbConnection(connectionStringInput))
using (OleDbCommand command = new OleDbCommand(queryString, connectionInput))
{
connectionInput.Open();
command.ExecuteNonQuery();
command.Dispose();
}
}
I haved checked sql string carefully (also in online checker).
I had also search on google's and found that this error, is probably connected with too many columns in my db, actually when I am opening db file, there is about 220 columns. But when I am counting columns programmaticly it shows that there is about 878 columns(before/after changing length of short string type in columns). For others tables it shows correct count.
I found that copying table, may help. But actually I also can't do that.
private void CopyDeleteCopyDeleteQuery(string tableName)
{
string queryString = "CREATE TABLE " + tableName + "O"+
" AS (SELECT * FROM " + tableName +
" WHERE CODE='0801733');";
using (OleDbConnection connectionInput = new OleDbConnection(connectionStringInput))
using (OleDbCommand command = new OleDbCommand(queryString, connectionInput))
{
connectionInput.Open();
command.ExecuteNonQuery();
command.Dispose();
}
}
System.Data.OleDb.OleDbException: 'Syntax error in CREATE TABLE statement.'
Query string :
CREATE TABLE CARTEO AS (SELECT * FROM CARTE WHERE CODE='0801733');
The limit for fields is 2kB (excluding Memo and OLE. With ~220 columns fields, you are likely to be hitting that limit.
You should normalize the table, or convert some columns to Memo fields.
I am having a problem inserting a record, the error says, "Error converting data type varchar to numeric."
This is my set of codes:
private void btnSearchCustomer_Click(object sender, EventArgs e)
{
//Get Customer Records
DataSet dsCustomer = new DataSet();
dsCustomer = GetRecords("Customers");
frmBasicSearch newSearch = new frmBasicSearch();
newSearch.myDataSet = dsCustomer;
newSearch.ShowDialog();
int myRowPosition = newSearch.myRowPosition;
if (myRowPosition != -1) //will display the value inside the textboxes
{
//concuntinated values
this.txtCustomerNo.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerNo"].ToString();
this.txtCustomerName.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerName"].ToString();
this.txtCustomerAddress.Text = dsCustomer.Tables["Customers"].Rows[myRowPosition]["CustomerAddress"].ToString();
groupProduct(true); //this will activate the buttons from the Product Section
}
cn.Close();
cn.Open();
SqlCommand cmdInsert = new SqlCommand();
cmdInsert.Connection = cn;
cmdInsert.Transaction = trnOrder;
cmdInsert.CommandType = CommandType.Text;
cmdInsert.CommandText =
"INSERT INTO ShoppingCart " +
"(OrderDate, CustomerNo, CustomerName, CustomerAddress, PurchaseOrderNo, AgentNo, AgentName, InvoiceNo, TotalAmount, OrderStatus) " +
"VALUES ('" +
dtpOrderDate.Value.Date.ToString() + "', '" +
txtCustomerNo.Text + "', '" +
txtCustomerName.Text + "', '" +
txtCustomerAddress.Text + "', '" +
txtPONo.Text + "', '0', 'Agent', '" +
txtInvoiceNo.Text + "', '" +
lblTotal.Text + "', 'Void'); " +
"SELECT TOP 1 ShoppingCartNo FROM ShoppingCart " +
"ORDER BY ShoppingCartNo DESC;";
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
txtOrderNo.Text = nShoppingCart.ToString();
cmdInsert.ExecuteNonQuery();
cn.Close();
}
the highlighted part is the
int nShoppingCart = Convert.ToInt16(cmdInsert.ExecuteScalar().ToString());
I cannot seem to know where is the problem? thank you for your help.
I think you have taken "CustomerNo" field in database numeric field and you are trying to insert varchar or string value in that field as i am able to see your code in which you are putting "txtCustomerNo.Text" which will contain string value. You should convert your value fisrt in int or whatever you have taken your database field.
Hopefully this will be helpful for you.
Can you run the script without the Convert method. Replace it with:
string nShoppingCart = cmdInsert.ExecuteScalar().ToString();
Then see what nShoppingCart value is, and see if that would ever convert to an integer.
Try adding following part
Convert.ToInt16(lblTotal.Text)
I'm currently finishing an asp.net project for a class and began to notice a major flaw with one of the requisites. The application should ask five questions and write the answers to a database, afterwards it should display the results of the survey to the user.
This is what I have attempted so far:
public static string GetConnectionString()
{
string connStr = String.Format("server={0}; user id={1}; password={2};" + "database= -table to be accessed-; pooling=false",
"-database server-", "-user-", "-password-");
return connStr;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string sex = gender.Text;
string likes = interests.Text;
string edu = education.Text;
string nation = nationality.Text;
string userage = age.Text;
MySql.Data.MySqlClient.MySqlConnection mycon;
mycon = new MySqlConnection(GetConnectionString());
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
cmd.ExecuteNonQuery();
mycon.Open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mycon.Close();
}
}
}
I went ahead and replaced the database information with placeholders.
The database is MySql and hosted on an external server.
The issue I'm experiencing is that the code compiles, however the information does not get written to the database. I'm not certain if this is due to the fact that I'm still testing the code and have not uploaded the web application to the server or the fact that it's just wrong.
As far as displaying the results go, if the above code is correct it would simply be a matter of changing the sql query, correct?
Thanks in advance for the insight.
You are executing the command before opening database connection.
ExecuteNonQuery() method and all other Execute method require an open database connection.
And another error is:
Number of columns (i.e. 5) and provided values (i.e. 4) are not equal.
And one more issue in your code is here as stated by Steve Wellens.
Change Your Code like below:
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
mycon.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
mycon.Close();
}
Security Notes:
Never add data into query using + operator. It may cause SQL Injection.
What if a user enters 1); DROP TABLE <table-name> -- in Age TextBox..??
Anyone can delete any table entirely from database.
Use MySQL Parameter to avoid such problems. It may prevent from causing serious damages to your entire database.
In your connection string:
"database= -table to be accessed-;
...you don't put the table. The table is specified in the SQL statement.
you should open the connect first, then execute the query.
try
{
MySqlCommand cmd = new MySqlCommand("INSERT INTO survey (gender, age, birthplace, occupation, winner) VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')", mycon);
mycon.Open();
cmd.ExecuteNonQuery();
}
This is likely not the only problem, but it is a problem:
"INSERT INTO survey (gender, age, birthplace, occupation, winner) " +
"VALUES ('" + sex + ", " + likes + ", " + edu + ", " + userage + "')",
(I've broken it into two strings to make it easier to read.)
You are inserting into five columns. You are only specifying four data values, and with the exception of gender they don't appear to be in the right order or even be the right data.
try checking these things :
try opening your connection before executing the SQL
check your SQL, and try execute them directly against the database. what i see in your SQL is you are concatenating the values into one string (quotes exist only in beginning and end, but not in between the parameters passed)
Ok new problem this is my full code I will explain what I'm trying to do and segment each part so you can see what it is I'm trying to achieve:
Full Code:
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
string theUserId = Session["UserID"].ToString();
OdbcConnection cn = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver}; Server=localhost; Database=gymwebsite2; User=x; Password=x;");
cn.Open();
OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
}
Ok the first part I'm trying to do is select the picture path related to the userid then if a userid is there with the same userid as im trying to upload delete the file that exists(not stored in database hence the IO) this part doesn't work the file pathname of the current userid isn't being deleted.
OdbcCommand sc = new OdbcCommand(string.Format("SELECT picturepath FROM Pictures WHERE UserID ='{0}'", theUserId), cn);
OdbcDataReader reader = sc.ExecuteReader();
while (reader.Read())
{
if (System.IO.File.Exists(Convert.ToString(reader[0])))
{
System.IO.File.Delete(Convert.ToString(reader[0]));
}
}
The second part just inserts the new file upload path and name into my database related to the current userid (this works) the file is uploaded to the correct folder and its inserted into my database. I could change this to UPDATE rather than insert but atm its either or not to fussy.
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId +
"/uploadedimage/") +
Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
StatusLabel.Text = "Upload status: File uploaded!";
OdbcCommand cmd = new OdbcCommand("INSERT INTO Pictures (UserID, picturepath) VALUES ('" + theUserId + "','" + fileuploadpaths + "')", cn);
cmd.ExecuteNonQuery();
So my problem is why is my if statement not deleting the currently held record in my database for the path of the current image? All that happens is my new image is uploaded into the same folder but the old image still remains?
Remember though I'm not trying to delete the "same" file name a simple saveas would overwrite it which is already in my code, what I need is for my code to delete any image that is currently in the userid specific folder when I'm trying to save the new image upload.
Any thoughts some help on the code?
Thanks guys
Looking at your code, I believe SystemDown has the answer in the comments:
When you save the file to disk you use the following code:
// Even though you've just calculated the result of Path.GetFileName you
// redo it here?
string fileuploadpath = Server.MapPath("~/userdata/" + theUserId
+ "/uploadedimage/")
+ Path.GetFileName(FileUploadControl.FileName);
FileUploadControl.SaveAs(fileuploadpath);
Then you store it in the DB as:
string filenameDB = Path.GetFileName(FileUploadControl.FileName);
string fileuploadpaths = ("~/userdata/" + theUserId + "/uploadedimage/") +
filenameDB;
However when you delete the file you're not performing Server.MapPath:
System.IO.File.Delete(Convert.ToString(reader[0]));
Change that line to:
System.IO.File.Delete(Server.MapPath(Convert.ToString(reader[0])));
And it should all work.
you should use the server.mappath to find that if image is already exist or not then try to delete that im