I'm new in c# and want to call store procedure in the sql server database ,for that purpose write this code:
using (SqlConnection con = new SqlConnection("Data Source=ipaddress;Initial Catalog=database;User ID=userid;Password=password;"))
{
using (SqlCommand cmd = new SqlCommand("exec web.sp_getTotalBillPayam "+Convert.ToInt64(phoneNumber) +",'"+password.Trim()+"',72107603,1067", con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
when run that code every thing is ok but store procedure not return to me any result ,goto debug i realized in this line run:
SqlDataReader reader = cmd.ExecuteReader();
but debugger not go to the next line of code and wait that line run finish,after 5 min that line not finish and dont go next line of code,what happen?How can i solve that problem?thanks.
Your command is not attached to your connection-- and your use of parameters is dangerous. Try this instead:
EDIT: Sorry, your command is attached to the connection, didn't see that being passed in. Either way, this is the correct pattern for calling a stored proc
using (SqlConnection con = new SqlConnection("Data Source=ipaddress;Initial Catalog=database;User ID=userid;Password=password;")) {
con.Open();
using (SqlCommand cmd = con.CreateCommand()) {
cmd.CommandText = "web.sp_getTotalBillPayam";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
//repeat this for each parameter
var parameter = cmd.CreateParameter();
parameter.ParameterName = "PhoneNumber"; //this must match whatever your parameters are to your stored proc
parameter.DbType = System.Data.DbType.Int64;
parameter.Direction = System.Data.ParameterDirection.Input;
parameter.Value = phoneNumber;
cmd.Parameters.Add(parameter);
...
//if you have an OUTPUT result from your proc, add a a parameter called RETURNS with a direction of ParameterDirection.Return and check value AFTER executing
using (SqlDataReader reader = cmd.ExecuteReader()) {
//if your results are a SELECT query they will be here
}
}
}
Related
I need to know why I am still getting this error
Stored procedure expects parameter which was not supplied
But I am actually sending this parameter.
The stored procedure in the database looks like this:
CREATE PROCEDURE SVC_BUSCA_MEDIO_LANDING
(#rut VARCHAR)
AS
BEGIN
SELECT utm_source
FROM landing_formulario
WHERE rut = #rut
END
And my .net code:
string result = string.Empty;
string connString = System.Configuration.ConfigurationManager.AppSettings["StPazWeb"].ToString();
string SVC_BUSCA_MEDIO_LANDING = "SVC_BUSCA_MEDIO_LANDING";
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
try
{
SqlCommand command = new SqlCommand(SVC_BUSCA_MEDIO_LANDING);
command.CommandType = CommandType.StoredProcedure;
command = new SqlCommand(command.CommandText, connection);
command.Parameters.AddWithValue("#rut", rut);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
result = (string)reader["utm_source"];
}
}
catch (SqlException ex)
{
throw new Exception("Oops!." + ex.Message);
}
}
return result.ToString();
Any idea what can be happening?
For some reason you create the command twice, with the second instantiation replacing the first, however on the second one you don't set the command type, and as a result your parameter is being ignored.
Try:
SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = SVC_BUSCA_MEDIO_LANDING;
command.Parameters.AddWithValue("#rut", rut);
You're using:
SqlCommand command = new SqlCommand(SVC_BUSCA_MEDIO_LANDING);
but you're reseting the command at:
command = new SqlCommand(command.CommandText, connection);
Try instead:
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SVC_BUSCA_MEDIO_LANDING";
command = new SqlCommand(command.CommandText, connection);
command.Parameters.AddWithValue("#rut", rut);
Below is a snapshot of my code. I am trying to access the only column in the customer table and place the values into a textbox on the form. I keep getting the error with my code "InvalidOperationException was unhandled" at the line declaring dr as a OleDbDataReader object.
What do I have wrong with the below code that would be giving me this error?
Should I do a list to pick out the text I want from the database?
How can I return the column values from access into a list in C# so that I can search the list for a particular value?
string strsql = "Select * from Customer";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
textBox1.Text += dr["Customer"].ToString();
}
conn.Close();
A command carries the info to be executed, a connection carries the info to reach the database server. The two objects should be linked together to produce any result. You miss that line
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = strsql;
cmd.Connection = conn; // <= here
conn.Open();
Remember also that disposable objects like a command, a reader and a connection should be disposed immediately after usage. For this pattern exists the using statement
So you should write
string cmdText = "Select * from Customer";
using(OleDbConnection conn = new OleDbConnection(.....constring...))
using(OleDbCommand cmd = new OleDbCommand(cmdText, conn))
{
conn.Open();
using(OleDbDataReader reader = cmd.ExecuteReader())
{
while(reader.Read())
.....
}
}
Here is some sample code.
try
{
using (OleDbConnection myConnection = new OleDbConnection())//make use of the using statement
{
myConnection.ConnectionString = myConnectionString;
myConnection.Open();//Open your connection
OleDbCommand cmdNotReturned = myConnection.CreateCommand();//Create a command
cmdNotReturned.CommandText = "someQuery";
OleDbDataReader readerNotReturned = cmdNotReturned.ExecuteReader(CommandBehavior.CloseConnection);
// close conn after complete
// Load the result into a DataTable
if (readerNotReturned != null) someDataTable.Load(readerNotReturned);
}
}
After that you have a Datatable containing your data. Ofcourse you can afterwards search for records in the Datatable any way you like.
I am getting following error when calling a stored procedure in SQL Server from C#:
Line 1: Incorrect syntax near 'spGet_Data'.
Here is my code:
public string GetData (string destinationFile)
{
string conectionString = "uid=One_User;pwd=One_Password;database=One_Database;server=One_Server";
SqlConnection con = new SqlConnection(conectionString);
SqlCommand sqlCmd = new SqlCommand();
string returnValue = string.Empty;
string procedureName = "spGet_Data";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.Parameters.AddWithValue("#FileName", destinationFile);
con.Open();
var returnParameter = sqlCmd.Parameters.Add("#ret", SqlDbType.VarChar);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.ExecuteNonQuery();
returnValue = returnParameter.Value.ToString();
con.Close();
return returnValue;
}
Procedure itself returning data properly, I checked connection it is in Open state.
What else it can be?
Thank you.
The problem lies in the fact that you create the command two times.
After the first initialization you set correctly the CommandType to StoredProcedure, but once again you created the command and this time you forgot to set the CommandType
Just remove the first initialization, leave only the second one and move the CommandType setting after the initialization
SqlConnection con = new SqlConnection(conectionString);
string returnValue = string.Empty;
string procedureName = "spGet_Data";
SqlCommand sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.CommandType = CommandType.StoredProcedure;
You create a SqlCommand object, then set it's CommandType property, then overwrite it by calling new on your command object again. Written out correctly, your code should look like this:
public string GetData (string destinationFile)
{
string conectionString = "uid=One_User;pwd=One_Password;database=One_Database;server=One_Server";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand sqlCmd = new SqlCommand(procedureName, con);
sqlCmd.CommandType = CommandType.StoredProcedure;
string returnValue = string.Empty;
string procedureName = "spGet_Data";
sqlCmd.Parameters.AddWithValue("#FileName", destinationFile);
con.Open();
var returnParameter = sqlCmd.Parameters.Add("#ret", SqlDbType.VarChar);
returnParameter.Direction = ParameterDirection.ReturnValue;
sqlCmd.ExecuteNonQuery();
returnValue = returnParameter.Value.ToString();
con.Close();
return returnValue;
}
Also, I would highly suggest that you surround your SqlConnection and SqlCommand objects with the Using Statement. Much like this:
public string GetData (string destinationFile)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand sqlCmd = new SqlCommand(procedureName, con))
{
}
}
}
The benefit of doing it this way is cleaner code and since your command and connection objects implement IDisposable, they will be handled by GC once they fall out of scope.
By the way, you have 'conectionString' misspelled; I fixed it in my code examples.
Whoops. This is being done, albeit incorrectly. See the other answer.
See SqlCommand.CommandType. You need to tell it to be treated as an sproc call. E.g.
sqlCmd.CommandType = CommandType.StoredProcedure;
Otherwise it results in an invalid SQL statement (i.e. running spGet_Data verbatim in an SSMS query should produce a similar messages).
I am having a problem with an Output parameter in C#/Oracle. I have isolated the code that I need to get working.
This is part of a much larger SQL statement, so do not worry too much if it doesn't make sense. In short I need to copy a row, give it a new ID and return that new ID. I tried using "RETURNING" which did not work. I see no reason why the code below should not work, but I'm getting an "ORA-01036: illegal variable name/number" error. Can anyone see what I'm doing wrong?
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "SELECT seq.nextval INTO :outValue FROM dual";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
// This is just to see the exception when it fails.
}
}
}
The name of the parameter doesn't match.
cmd.Parameters.Add(":outValue", OracleType.Int32).Direction.......;
^
I have also seen this variation on the query syntax
"BEGIN SELECT seq.nextval INTO :outValue FROM dual END;"
You are using named parameters. Try setting:
cmd.BindByName = true;
Have you tried 'returning' keyword like this?
This code works for me.
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "insert into table (id, value) values (seq.nextval, 'value') returning id into :outValue";
cmd.ExecuteNonQuery();
}
}
This is a really, really stupid question but I am so accustomed to using linq / other methods for connecting and querying a database that I never stopped to learn how to do it from the ground up.
Question: How do I establish a manual connection to a database and pass it a string param in C#? (yes, I know.. pure ignorance).
Thanks
using (SqlConnection conn = new SqlConnection(databaseConnectionString))
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "StoredProcedureName";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ID", fileID);
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
// process row from resultset;
}
}
}
}
One uses the SqlCommand class to execute commands (either stored procedures or sql) on SQL Server using ado.net. Tutorials abound.
Here's an example from http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx
public void RunStoredProcParams()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
// typically obtained from user
// input, but we take a short cut
string custId = "FURIB";
Console.WriteLine("\nCustomer Order History:\n");
try
{
// create and open a connection object
conn = new
SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();
// 1. create a command object identifying
// the stored procedure
SqlCommand cmd = new SqlCommand(
"CustOrderHist", conn);
// 2. set the command object so it knows
// to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which
// will be passed to the stored procedure
cmd.Parameters.Add(
new SqlParameter("#CustomerID", custId));
// execute the command
rdr = cmd.ExecuteReader();
// iterate through results, printing each to console
while (rdr.Read())
{
Console.WriteLine(
"Product: {0,-35} Total: {1,2}",
rdr["ProductName"],
rdr["Total"]);
}
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
3 things no one else has shown you yet:
"Stacking" using statements
Setting an explicit parameter type rather than letting .Net try to pick one for you
"var" keyword
.
string sql = "MyProcedureName";
using (var cn = new SqlConnection(databaseConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ParameterName", SqlDbType.VarChar, 50)
.Value = "MyParameterValue";
conn.Open();
using (SqlDataReader rdr =
cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
if (rdr.Read())
{
// process row from resultset;
}
}
}