How to insert image in oracle database in c# .net application - c#

When i tried to insert, the error 'not enough values' appears.
public int CreateAdmin( string product_name, string quality, string quantity, string price, string product_image)
{
string connectionString = "User Id=hr;Password=hr;Data Source=localhost:1521/xe";
OracleConnection orc = new OracleConnection();
orc.ConnectionString = connectionString; //assign connection
//OracleDataAdapter da = new OracleDataAdapter();
orc.Open();
OracleCommand cmd = new OracleCommand();//object of command
cmd.Connection = orc;
cmd.CommandType = CommandType.Text; // declare command type
cmd.CommandText = "insert into Product values( :b, :c, :d, :a, :p)";
cmd.Parameters.Add("#b", product_name); //add paramenter
cmd.Parameters.Add("#c", quality);
cmd.Parameters.Add("#d", quantity);
cmd.Parameters.Add("#a", price);
cmd.Parameters.Add("#p", product_image);
//da.InsertCommand = cmd;
int i = cmd.ExecuteNonQuery();
orc.Close();
return i;
}

Your paramnames are wrong, they need to be named as the one you set in params - you use :a in the command and #a when setting the parameter. Parameter start with # (for SqlServer) or : (for OracleServer).
If your table has more columns than those 5 you have to provide them as well, else the db does not know where to put the given parameters. (an auto-inc ID additionally is fine, if thats your 6th column it will work).
public int CreateAdmin (string product_name, string quality, string quantity, string price, string product_image)
{
string connectionString = "User Id=hr;Password=hr;Data Source=localhost:1521/xe";
using (var orc = new OracleConnection (connectionString))
{
using (var cmd = orc.CreateCommand ())
{
cmd.CommandType = CommandType.Text; // declare command type
// Product has exactly 5 or 5 + 1 auto-inc ID column, else provide the
// column names as well:
// insert into Product ( name,qual,quant,price,img ) values( :b, :c, :d, :a, :p)";
cmd.CommandText = "insert into Product values( :b, :c, :d, :a, :p)";
cmd.Parameters.Add (":b", product_name); //add paramenter
cmd.Parameters.Add (":c", quality);
cmd.Parameters.Add (":d", quantity);
cmd.Parameters.Add (":a", price);
cmd.Parameters.Add (":p", product_image);
//da.InsertCommand = cmd;
int i = cmd.ExecuteNonQuery ();
return i;
}
}
}
I changed your code to benefit from using(var orc = new OracleConnection()) { .... }-pattern with IDisposables - it auto-close/disposes your connection (same for command) on leaving the scope.
Edited due to comment by Wernfried-Domscheit:
Oracle needs : (# is for SqlServer) - this answer how-to-write-parameterized-oracle-insert-query supports it - it even uses parameter names without : - so perhaps parameternames are just inserted by "order" instead of "by name"

You have two options for saving an image to your DB:
Convert your image to Base64 and save the output string to your DB
Save your image as a file on your server and save the path of this image to your DB (Recommended)

You will most likely have more columns in your Product table than you give in your values list. Explicitly give column names:
OracleCommand cmd = new OracleCommand();//object of command
cmd.Connection = orc;
cmd.CommandType = CommandType.Text; // declare command type
// explicitly add column names
cmd.CommandText = "insert into Product (product_name, quality, quantity, price, product_image) values( :b, :c, :d, :a, :p)";
cmd.Parameters.Add(":b", product_name); //add paramenter
cmd.Parameters.Add(":c", quality);
cmd.Parameters.Add(":d", quantity);
cmd.Parameters.Add(":a", price);
cmd.Parameters.Add(":p", product_image);
int i = cmd.ExecuteNonQuery();
Please change the column names in the above code to match your column names in your table. Let us know if that worked for you.
Edit
As stated by Patrick Artner in his well-written answer, the parameter name placeholders had to be the same in the CommandText and when adding the parameters to the command. When using OracleCommand, the placeholder needs to be : rather than # as stated in the MSDN OracleCommand.Parameters page.

Related

"Syntax error in INSERT INTO statement" when adding record to Access database

I've searched for hours for a solution to this problem but nothing I've read has helped. I'm getting this error when trying to add this record to an Access database. The file I'm trying to save into is named Cats.accdb, with a table named Cats.
Table column names:
CatId (type: text) CatName (text) Hair (text) Size (text) CareType (text) Notes (text)
AdoptDate (date/time general date), Weight (double), Age (integer) (I've commented any reference to these columns out in the C# code to attempt to debug with just plain old text boxes. At first I thought it was because of something to do with using a DateTimePicker, but it still throws the error after commenting out.)
C# code:
Cat temp = new Cat(txtCatName.Text, txtHair.Text, txtSize.Text, txtCareType.Text, txtNotes.Text);
public string AddCat()
{
string strFeedback = "";
string strSQL = "INSERT INTO Cats (CatName, Hair, Size, CareType, Notes) VALUES (#CatName, #Hair, #Size, #CareType, #Notes)";
OleDbConnection conn = new OleDbConnection();
string strConn = #"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Data\Cats.accdb; Persist Security Info=False;";
conn.ConnectionString = strConn;
OleDbCommand comm = new OleDbCommand();
comm.CommandText = strSQL;
comm.Connection = conn;
comm.Parameters.AddWithValue("#CatName", CatName);
comm.Parameters.AddWithValue("#Hair", Hair);
comm.Parameters.AddWithValue("#Size", Size);
comm.Parameters.AddWithValue("#CareType", CareType);
comm.Parameters.AddWithValue("#Notes", Notes);
//comm.Parameters.AddWithValue("#AdoptDate", AdoptDate);
//comm.Parameters.AddWithValue("#Weight", Weight);
//comm.Parameters.AddWithValue("#Age", Age);
{
conn.Open();
strFeedback = comm.ExecuteNonQuery().ToString() + " record has been added successfully!";
conn.Close();
}
catch (Exception err)
{
strFeedback = "ERROR: " + err.Message;
}
return strFeedback;
lblFeedback.Text = temp.AddCat();
Thanks for any help you can give!
Size is a reserved keyword. Add brackets around the name to specify that it's an identifier:
string strSQL = "INSERT INTO Cats (CatName, Hair, [Size], CareType, Notes) VALUES (#CatName, #Hair, #Size, #CareType, #Notes)";
Alternatively, change the field name to something that is not a keyword.
In MS Access OLEDB I believe you use position markers rather than parameter names.
string strSQL = "INSERT INTO Cats (CatName, Hair, Size, CareType, Notes) VALUES (?, ?, ?, ?, ?)";

Convert ID to Int and save to datatable

I have been trying to add the Customer_ID from the Customer table to Customer_ID in Customer_Ship table. I keep running into the Customer_ID not converting to Int properly. It's possible that I am not actually getting the new row added to Customer_Ship table first. Your help is greatly appreciated and many thanks in advance.
if (customer_ID == "")
{
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name); SELECT Customer_ID FROM Customer WHERE Customer_ID = SCOPE_IDENTITY();";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int customer_Id = (int)sqlCommand.ExecuteScalar();
SQL = "INSERT INTO Customer_Ship (Customer_ID) VALUES (#customer_Id)";
sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.AddwithValue("#customer_Id", customer_Id);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
}
Two mistakes I see:
you should be just returning SCOPE_IDENTITY - you can simplify your first INSERT statement to read:
INSERT INTO Customer (Customer_Name) VALUES (#customer_Name); SELECT SCOPE_IDENTITY();";
This will return the newly inserted Customer_ID identity value from the Customer table - no need to do this complicated SELECT that you had in your question
You need to call .ExecuteScalar() right from the beginning - don't call .ExecuteNonQuery() first and then ExecuteScalar() - that'll execute the statement twice - just use:
using(SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection))
{
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int customer_Id = (int)sqlCommand.ExecuteScalar();
sqlConnection.Close();
}
That'll insert the values into Customer and return the newly created Customer_ID as the return value into customer_id (which already is an Int) from .ExecuteScalar(). You can then use this int value to insert into the Customer_Ship table - no conversion necessary - this already is an int
The possible reason for not converting the value is you are trying to convert an empty string(customer_ID : Refer Line :#1 of your code) and not "customer_Id " what you are fetching from the database .

Insert statement into SQL Server db

I'm developing an ASP.NET MVC Web Application using SQL Server.
I am trying to INSERT a new entry into my database and I don't understand what am I doing wrong.
I get an exception on the line:
command.ExecuteNonQuery();
The code is:
try
{
SqlConnection connection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=UniversityManager;Integrated Security=True");
using (connection)
{
//SqlCommand command = new SqlCommand(
// "INSERT INTO Students VALUES(#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp);",
// connection);
connection.Open();
String sql = "INSERT INTO Students(Id,Name,Surname,Year,PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#Id", SqlDbType.Int);
command.Parameters["#Id"].Value = 5;
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = collection.Name;
command.Parameters.Add("#Surname", SqlDbType.VarChar);
command.Parameters["#Surname"].Value = collection.Surname;
command.Parameters.Add("#Year", SqlDbType.Int);
command.Parameters["#Year"].Value = collection.Year;
command.Parameters.Add("#PhoneNumber", SqlDbType.VarChar);
command.Parameters["#PhoneNumber"].Value = collection.PhoneNumber;
command.Parameters.Add("#Cnp", SqlDbType.VarChar);
command.Parameters["#Cnp"].Value = collection.Cnp;
command.ExecuteNonQuery();
connection.Close();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Thank you!
YEAR is a reserved keyword for Sql Server. So, if you really have a column with that name, then you need to enclose it in square brackets every time you refer to it. Better change that name
String sql = "INSERT INTO Students(Id,Name,Surname,[Year],PhoneNumber,Cnp) " +
"VALUES (#Id, #Name, #Surname, #Year, #PhoneNumber, #Cnp)";
Another possibility is the Id column. If this column has the IDENTITY property set to true, then you should not set a value for it. It is automatically calculated by the database engine.
Looking at your innerexception message, it seems the problem is due to one or more of your parameters contains more text than allowed by the database field size.
You could try something like this (for each varchar parameter)
// Assuming the Name field is defined as varchar(15)
command.Parameters.Add("#Name", SqlDbType.VarChar, 15);
command.Parameters["#Name"].Value = collection.Name;
The String or binary data would be truncated exception means you're trying to insert a value that is too large for one of the columns in your Student table. For example, your Name field has a maximum length of 10 but you're trying to insert a 15 character name.
Check the values you're inserting and see if they're too large for the columns.

SQL server - inserting a string with a single quotation mark

I iterate over an external source and get a list of strings. I then insert them into the DB using:
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
Where commandString is an insert into command. i.e.
insert into MyTable values (1, "Frog")
Sometimes the string contains ' or " or \ and the insert fails.
Is there an elegant way to solve this (i.e. #"" or similar)?
Parameters.
insert into MyTable values (#id, #name)
And
int id = 1;
string name = "Fred";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("name", name);
command.ExecuteNonQuery();
Now name can have any number of quotes and it'll work fine. More importantly it is now safe from sql injection.
Tools like "dapper" (freely available on NuGet) make this easier:
int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (#id, #name)",
new { id, name });
You should look into using parameterized queries. This will allow you insert the data no matter the content and also help you avoid possible future SQL injection.
http://csharp-station.com/Tutorial/AdoDotNet/Lesson06
http://www.c-sharpcorner.com/uploadfile/puranindia/parameterized-query-and-sql-injection-attacks/

System.Data.OleDb.OleDbException: Number of query values and destination fields are not the same

I received some help which I much appreciate to insert info into a database using paramaters as it is better practice I believe to do this.
I do however get the following error 'Number of query values and destination fields are not the same'. Not sure as to why it is happening.
The code seems perfectly fine and the database.
[WebMethod]
public void bookRatedAdd(string title, int rating, string review, string ISBN, string userName)
{
OleDbConnection conn;
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source=" + Server.MapPath("App_Data\\BookRateInitial.mdb"));
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])VALUES(#title, #rating. #review, #ISBN, #userName)";
//adding my parameters
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#title", title),
new OleDbParameter("#rating", rating),
new OleDbParameter("#review", review),
new OleDbParameter("#ISBN", ISBN),
new OleDbParameter("#userName", userName),
});
cmd.ExecuteNonQuery();
conn.Close();
}
Advice perhaps as to why this error exist?
Kind regards
Arian
There is a . (period) instead of a , (comma) in your INSERT statement after the #rating parameter.
Change the . to comma.
INSERT INTO bookRated([title], [rating], [review], [frnISBN], [frnUserName])
VALUES(#title, #rating, #review, #ISBN, #userName)
I think this may be as simple as that a period has been put in place of a comma where the parameters are specified:
#rating. #review
should be:
#rating, #review

Categories

Resources