Unable to insert data to database in asp.net C# - c#

I'm new in C# programming, so I'll appreciate if anyone can help me. I know there are similar question but I still can't find the solution for my problem. I'm developing a mock system, where when user bought the product, the system will store all the transaction details. the problem is, I cannot insert the data into the database. Here's the code:
using (SqlConnection conn = new SqlConnection
(ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
string QueryA = "#Insert into TransDetails(AccountNumber,Amount,Provider"
+ ",Mobile Number,TransNum,TransDate, Status) "
+ " Values (#AccountNumber,#Amount,#Provider,#Mobile Number,"
+ "#TransNum,#TransDate,#Status";
using (SqlCommand cmd = new SqlCommand("InsertRecord", conn))
{
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.CommandText = QueryA;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
}
and the stores procedures are as follows:
ALTER PROCEDURE InsertRecord1
#AccountNumber int,
#Amount nchar(10),
#Provider nchar(10),
#MobileNumber int,
#TransNum nchar(10),
#TransDate date,
#Status nchar(10)
AS
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,TransNum,TransDate,Status)
Values (#AccountNumber,#Amount,#Provider,#MobileNumber,#TransNum,#TransDate,#Status)
return
Really appreciate any help.
P/S: i dont know why the beginning of the stored procedures started with "alter".

I may be reading it wrong, but it looks like your stored procedure is not used at all. Try commenting out "cmd.CommandText = QueryA;" and substitute "cmd.CommandText = "InsertRecord1";" and change CommandType to StoredProcedure.
QueryA, by the way, is missing a paren at the end. However, the whole thing is unnecessary since you have a stored procedure that does the same thing and it's almost always preferable to use a stored procedure rather than embedded DML.

You must escape Mobile Number while brackets
Insert into TransDetails(AccountNumber,Amount,Provider,[Mobile Number],...
and remove the space in your parameter
...,#MobileNumber,#TransNum,#TransDate,#Status
and change the paramname in your command parameter
cmd.Parameters.AddWithValue("#MobileNumber", lblNumber.Text);
but seeing your stored procedure, the column Mobile Number has no space between it. Is it a typo error in your query on QueryA? If it is, then remove the space on it (also on parameter name)
Insert into TransDetails(AccountNumber,Amount,Provider,MobileNumber,...
or
change your CommandType.Text to CommandType.StoredProcedure and remove this line,
cmd.CommandText = QueryA;

You're using the wrong overload of the SqlCommand constructor. According to MSDN:
new SqlCommand(string, SqlConnection) Initializes a new instance of the SqlCommand class with the text of the query and a SqlConnection.
What you need to do is either set your CommandType for the sql command to CommandType.StoredProcedure and not use QueryA, or initialize the sql command with QueryA and not make use of your stored procedure.

As you can see there is # at the start of your SQL Statement.
Also you are not really using the Store Procedure.

You can Try this:
using (SqlConnection conn = new SqlConnection (ConfigurationManager.ConnectionStrings["database"].ConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("InsertRecord1", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#AccountNumber", acc.Text);
cmd.Parameters.AddWithValue("#Amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#Provider", lblProvider.Text);
cmd.Parameters.AddWithValue("#Mobile Number", lblNumber.Text);
cmd.Parameters.AddWithValue("#TransNum", lblTrans.Text);
cmd.Parameters.AddWithValue("#TransDate", lblDate.Text);
cmd.Parameters.AddWithValue("#Status", status.Text);
try
{
cmd.ExecuteNonQuery();
}
catch
{
lblMessage.Text = "Error";
}
finally
{
conn.Close();
}
}
Tho I don't use SQL Commands, Adapters...etc. to access the data from the SQL Database. I prefer Microsoft Data Access ApplicationBlocks which is easy-to-use library provided by Microsoft to access data from SQL Server.
Download
You can download it here http://download.microsoft.com/download/VisualStudioNET/daabref/RTM/NT5/EN-US/DataAccessApplicationBlock.msi
Introduction
https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx

Related

How can I get multiple output parameters from a stored procedure in a web service in C#?

I have a web service in C#, I use it to consults from tables, but I want to create a WebMethod to call a stored procedure and get back multiples output parameters. I can execute it with output parameters, it doesn't work when I try to call it whit outputs parameters.
This is a sample, I want to get back more that 2 parameters.
Stored procedure:
CREATE OR REPLACE PROCEDURE O_CAPEREZ.GIO_SP (
VNOMBRE IN VARCHAR2,
SALUDO OUT VARCHAR2 )
AS
BEGIN
INSERT INTO G_PRUEBA_SP(NOMBRE)
VALUES (vNOMBRE);
SALUDO:= ('Hello: ' || vNOMBRE);
END;
And this is my code in the web service, when I execute it using output variables I get this error
[HYC00] [Oracle][ODBC]Optional feature not implemented
C# code:
[WebMethod]
public string AP_Data(string curp)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (OdbcConnection con = new OdbcConnection(constr))
{
OdbcCommand cmd = new OdbcCommand("{CALL GIO_SP(?,?)}", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#vNOMBRE", (curp));
cmd.Parameters.Add("#vNOMBRE", OdbcType.VarChar, 18);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Parameters["#SALUDO"].Direction = ParameterDirection.ReturnValue;
cmd.Connection.Close();
string ret = Convert.ToString(cmd.Parameters["#SALUDO"].Value);
return ret;
}
}
You have to add the parameter to the list even if you're not going to set a value there:
cmd.Parameters.Add("#SALUDO", OdbcType.VarChar, 18).Direction = ParameterDirection.Output;
I don't know the the Oracle flavor is different, but in SQL I use ParameterDirection.ReturnValue rather than ParameterDirection.Output.
here's how i do it in MS SQL server 2008 But notice the data type and the lenth of the variables your create must be the same in your table
the stored proc create code
USE DATABASE DATABASE_NAME
GO
CREATE PROC SP_METHOD
#ID_CATIGORY INT,
#NAME VARCHAR (50),
#DESCRIPTION VARCHAR (50)
AS
INSERT INTO TABLE_NAME
([ID_CAT]
,[NAME_PRODUCT]
,[DESC_PRODUCT]
)
VALUES
( #ID_CATIGORY
,#NAME
,#DESCRIPTION )
GO
in the c# code
// Create SqlConnection
SqlConnection conn= new SqlConnection(#"Server=server_name;
DataBase=your_data_base_name;Integrated Security=false;User
Id=user_id;Password=password");
// Open the Connection
if (sqlconnection.State != ConnectionState.Open)
{
conn= .Open();
}
// execute stored_procedure method don't change this
public void ExecuteCommand(string stored_procedure, SqlParameter[] param)
{
SqlCommand sqlcomd = new SqlCommand();
sqlcomd.CommandType = CommandType.StoredProcedure;
sqlcomd.CommandText = stored_procedure;
sqlcomd.Connection = sqlconnection;
if (param !=null)
{
sqlcomd.Parameters.AddRange(param);
}
sqlcomd.ExecuteNonQuery();
}
// close connection method
public void close_conn()
{
if (sqlconnection.State == ConnectionState.Open)
{
sqlconnection.Close();
}
}
// execute and retrieving data Method
public void Add_product(int ID_cat ,string Name_Product,string
Des_Product)
{
SqlParameter[] param = new SqlParameter[3];
param[0] = new SqlParameter("#ID_CAT", SqlDbType.Int);
param[0].Value = ID_cat;
param[1] = new SqlParameter("#NAME_PRODUCT", SqlDbType.VarChar, 50);
param[1].Value = Name_Product;
param[2] = new SqlParameter("#DESC_PRODUCT", SqlDbType.VarChar, 50);
param[2].Value = Des_Product;
ExecuteCommand("StoredProcedure_name", param);
close_conn();
}
and finally you can call this function
Add_product(Convert.ToInt32(ComboBox.SelectedValue),txt_name.Text,
txt_desc.Text);
if there is any part you don't understand lemme know
I've seen many ways to accomplish this.
One way is to Pipe Delimit your select statement in your stored procedure and then use "Value1|Value2".Split('|')[0] to get Value1.
You could also return a table instead of using multiple parameters
DataTable table = new DataTable();
DataAdapter adapter = new DataAdapter(cmd);
adapter.fill(table);
return table.Rows[0]["Greeting"] + table.Rows[0]["Name"];
In the second example you can return as many 'Parameters' as you want, but you will have to assign them to their rightful spots later in your code.
I've also seen an XML way to do this same feature but I won't provide the code here since I don't personally think it is a very good way to do it. The way I've seen done was adding a bunch of XML attributes to a parent tag, and then coming back later and finding the value of each tag later in the code.
In MYSQL it would go like this
CREATE PROCEDURE O_CAPEREZ.GIO_SP (
#vNOMBRE VARCHAR(50))
AS
BEGIN
INSERT INTO G_PRUEBA_SP(NOMBRE)
VALUES (#vNOMBRE);
select 'Hola' as Greeting, #vNOMBRE as Name
END
Also note what Marc_s commented
You need to set the .Direction of the parameter BEFORE making the call to .ExecuteNonQuery()

Insert a file path string into SQL database via C# code

In SQL:
INSERT INTO [dbo].[tblFiles]
([FullFilePath]
,[LastModified])
VALUES
('P:\test\test.csv',
null)
This will store the full path in the database :)
However, I need to do this in code.
SqlConnection connection = new SqlConnection(DatabaseHelper.ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand( "stpInsertFile", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#filepath", System.Data.SqlDbType.VarChar));
command.Parameters["#filepath"].Value = article.FullFilePath;
command.Parameters.Add(new SqlParameter( "#LastModified", System.Data.SqlDbType.DateTime));
command.Parameters["#LastModified"].Value = article.LastModified;
int newArticleID = Convert.ToInt32((decimal)command.ExecuteNonQuery());
command.Dispose();
connection.Close();
connection.Dispose();
return newArticleID;
With this all I get is 'P' in the full path column.
So I tried using LINQ and got the same result.
public int InsertArticleUsingLINQ(tblFile article) {
DataClassesDataContext context = new DataClassesDataContext();
tblFile newFileEntry = new tblFile();
newFileEntry.FullFilePath = article.FullFilePath;
newFileEntry.LastModified = article.LastModified;
context.tblFiles.InsertOnSubmit(newFileEntry);
context.SubmitChanges();
return newFileEntry.ID;
}
I'm not doing anything with the string before passing it to the database insert functions. I read that you need to escape the backslash but it seems to be escaping on the quote. Also read that you need an # symbol before the sql but how do you add this to a parameter?
warning: since you didn't share the stored procedure code this is just a wild guess.
did you set the size of the #filePath parameter in the definition of your stored procedure?
if you declare it as:
create procedure stpInsertFile
#filepath varchar,
#LastModified datetime
as
...
then you parameter is created as varchar(1) because of the default behaviour of varchar datatype and that would produce the result you get.please check reference documentation for char and varchar datatype on ms website.
if stpInsertFile is a Stored Procedure you will have to set in your code:
...
command.CommandType = CommandType.StoredProcedure;
else you have to set the query string in your command:
SqlCommand command = new SqlCommand( "INSERT INTO [dbo].[tblFiles] ([FullFilePath] [LastModified]) VALUES (#filepath,#LastModified)", connection);
...
Of the above options, the ADO code did not copy the full path, even with manually adding quotes. All I ever got was one character in the database.
On further inspection, the parameter was of type Varchar(1) !!! I changed this to Varchar(255) an it worked.
Note, the LINQ to SQL function did insert the full path as this was not using the Stored Procedure.
Apologies for the mistake.

C# ADO.NET - Could Not Find Stored Procedure

I am trying to execute a stored procedure through C#, ADO.NET and below is the code I am trying to execute:
using (SqlConnection conn = new SqlConnection(".;Initial Catalog=MyDB;User ID=sa;Password=***"))
{
try
{
string cmdText = "dbo.sp_Create_FlaggedItemEntry #URI, #ID";
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
cmd.CommandText = cmdText;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#URI", value1);
cmd.Parameters.AddWithValue("#ID", value2);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Now when I try to debug it, I got an error at the line - cmd.ExecuteNonQuery(); - "Could Not Find Stored Procedure dbo.sp_Create_FlaggedItemEntry"
I verified that the Connection String is all correct and Stored Procedure exists.
Further, If I change the line - cmd.CommandType = CommandType.StoredProcedure; to cmd.CommandType = CommandType.Text; it get executed successfully and as expected.
Can someone suggest what I am missing and doing wrong here - Please pardon me if it is something very basic as it is quite long since I last worked with ADO.NET
CommandType.StoredProcedure means that the CommandText should only contain the name of the stored procedure.
Remove the parameter names from the string.
Take the parameters out of the command text. Also, you don't need to specify dbo.
The reason it's working with CommandType.Text is because it's a legitimate SQL command like that - if you were to open up SSMS and type that in it'd work as long as you also create the variables #URI and #ID
Documentation here
You should mention Data Source / Server in connectionString. Also for CommandText #Slaks is correct.

StoredProcedure with Mono c#?

Can I use MySql Stored Procedure for my Mono C# Gtk+ app for Ubuntu?
I have try with..
using MySql.Data.MySqlClient;
// Prepare connecting to the database.
myConn = new MySqlConnection("server=localhost;database=table;uid=root;password=1234;");
cmd = myConn.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = #"Call newRow()";
myConn.Open();
cmd.ExecuteNonQuery();
myConn.Close();
If I just make and hardcode sql string in my program, it work!
Like..
cmd.CommandText = #"insert into table ...
The problem is with the:
cmd.CommandType = CommandType.StoredProcedure
-Line.
If you get an error with the Open call, your connection string is wrong. That has nothing to do with your command.
That said, I think your command should only contain the stored procedures name. Just "newRow" without any additional database syntax like call or empty brackets.
Ok so.. Just remove the..
cmd.CommandType = CommandType.StoredProcedure
The MySql.Data.MySqlClient do not need this option to do Stored Procedure :)

C# Oracle execute stored procedure with output parameter

Situation:
I'm trying to run a stored procedure that has an output parameter, which I need to catch.
I use C# 3.5 and the OracleClient with an OleDbConnection.
Research:
I've been looking around for other ways, but as far as I can tell I'm doing it correct. Microsoft support and various other forums.
Problem:
When I do the cmd.ExecuteNonQuery() it just gets stuck. No error or anything, it just stops there and holds the Thread.
When I try via OleDbDataReader or the Scalar it's nothing better.
If I change the CommandText (remove package name) it gives error that it can't find the stored procedure, so I know that is correct at least.
Code:
Oracle:
PROCEDURE deleteThemakaart
(an_seqthemakaart IN NUMBER, an_retval OUT NUMBER)
....
C#:
double InputValue = 777;
try
{
OleDbConnection con = new OleDbConnection(...);
con.Open();
OleDbCommand cmd = new OleDbCommand()
{
CommandText = "thema.pckg_themakaarten.deleteThemakaart",
Connection = con,
CommandType = CommandType.StoredProcedure,
};
OleDbParameter input = cmd.Parameters.Add("an_seqthemakaart", OleDbType.Double);
OleDbParameter output = cmd.Parameters.Add("an_retval", OleDbType.Double);
input.Direction = ParameterDirection.Input;
output.Direction = ParameterDirection.Output;
input.Value = InputValue;
cmd.ExecuteNonQuery();
return (double)output.Value;
}
catch (Exception ex)
{
...
}
finally
{
con.Close();
}
Any help is very welcome :)
Edit: some code is below in comment, but hasn't gotten me any further so far :(
Greetings
I found the trouble maker... one of the tables that the procedure used was locked.

Categories

Resources