Is there a way to add OPTION (RECOMPILE) in C# while executing stored procedure by System.Data.SqlClient?
What I'm looking for in my imagination would be something like
using (SqlConnection sqlConn = new SqlConnection(CONN_STR))
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("usp_xyz OPTION (RECOMPILE)", sqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("x", x);
cmd.ExecuteNonQuery();
}
}
Yes, you can use the EXEC... WITH RECOMPILE syntax, but you must do it as an ad-hoc batch, and therefore specify all parameters. You cannot use this with CommandType.StoredProcedure.
using (SqlConnection sqlConn = new SqlConnection(CONN_STR))
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("EXEC usp_xyz #x = #x WITH RECOMPILE;", sqlConn))
{
cmd.Parameters.Add("#x", SqlDbType.SomeType, SomeLength).Value = x;
cmd.ExecuteNonQuery();
}
}
If you want, you could use sp_recompile, but this has different semantics: it does not just generate a new plan for this run, it discards the old plan for all future runs of the procedure.
using (SqlConnection sqlConn = new SqlConnection(CONN_STR))
{
sqlConn.Open();
using (SqlCommand cmd = new SqlCommand("sp_recompile", sqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#objname", SqlDbType.NVarChar, 776).Value = "dbo.usp_xyz";
cmd.ExecuteNonQuery();
}
using (SqlCommand cmd = new SqlCommand("usp_xyz", sqlConn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#x", SqlDbType.SomeType, SomeLength).Value = x;
cmd.ExecuteNonQuery();
}
}
Related
I have a problem in SqlDataReader - it cannot proceed into while and cannot while.
Here is my code
List<tmp_WatchList> data = new List<tmp_WatchList>();
using (SqlConnection con = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand("sp_CheckPersonList", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
SqlDataReader oReader = cmd.ExecuteReader();
while (oReader.Read())
{
//data.Add(new tmp_WatchList
//{
tmp_WatchList l = new tmp_WatchList();
l.id = int.Parse(oReader["id"].ToString());
l.Name = oReader.GetValue(1).ToString();
l.Crime = int.Parse(oReader.GetValue(2).ToString());
data.Add(l);
///});
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
con.Close();
}
}
}
and my stored procedure is:
ALTER PROCEDURE [dbo].[sp_CheckPersonList]
(#Name NVARCHAR(MAX) NULL)
AS
BEGIN
SELECT REPLACE(Name, '.', ''), Crime
FROM [dbo].[tmp_WatchList]
WHERE [Name] LIKE CONCAT('%', REPLACE(#Name, ' ', '%'), '%')
END
Can you tell me how it is done? Or is something wrong with my structure?
You are not opening the connection any where before calling the ExecuteReader, you need to open the database connection, following is the lineo of code to open the connection :
con.Open(); // open connection
SqlDataReader oReader = cmd.ExecuteReader(); // now execute SP
and you do not need finally block for closing the connection, as you are already applyuing the using block on your SqlConnection and SqlCommand which is converted by compiler in to try finally which takes care of disposing the resources and in case of SqlConnection closing the connection.
As other have pointed out, you need to Open the connection, and you can simplify your code removing the try/catch/finally and the explicit con.Close(), which you don't need since you are (corretcly) wrapping the connection within a using
Your code should be something like this (much cleaner than the original one after removing the try/catch/finally):
List<tmp_WatchList> data = new List<tmp_WatchList>();
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("sp_CheckPersonList", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = name;
SqlDataReader oReader = cmd.ExecuteReader();
while (oReader.Read())
{
tmp_WatchList l = new tmp_WatchList();
l.id = int.Parse(oReader["id"].ToString());
l.Name = oReader.GetValue(1).ToString();
l.Crime = int.Parse(oReader.GetValue(2).ToString());
data.Add(l);
}
}
}
If that code raises an exception, it will simply be forwarded to the caller, in a better way comparing to what you did with your throw new Exception(exc.Message), which will loose the original stack trace
Remove the unwanted code..Try Like this..
List<tmp_WatchList> data = new List<tmp_WatchList>();
SqlConnection con = new SqlConnection(conStr);
SqlCommand cmd=new SqlCommand();
cmd.CommmandText="sp_CheckPersonList";
cmd.CommandType = CommandType.Text;
con.Open();
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name",name);
SqlDataReader oReader = cmd.ExecuteReader();
while (oReader.Read())
{
tmp_WatchList l = new tmp_WatchList();
l.id = int.Parse(oReader["id"].ToString());
l.Name = oReader.GetValue(1).ToString();
l.Crime = int.Parse(oReader.GetValue(2).ToString());
data.Add(l);
}
oReader.Close();
Con.Close();
I'm trying to prevent SQL injections. Am I doing this right? (I'm using MS Access.) Should I still use sqlparameter?
OleDbParameter[] myparm = new OleDbParameter[2];
myparm[0] = new OleDbParameter("#UserID", UserName.Text);
myparm[1] = new OleDbParameter("#Password", encode);
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
Close!
string queryStr = "SELECT * FROM TMUser WHERE UserID=#UserID AND Password=#Password";
OleDbConnection conn = new OleDbConnection(_connStr);
OleDbCommand cmd = new OleDbCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#UserID", UserName.Text);
cmd.Parameters.AddWithValue("#Password", encode);
The parameters are part of the command object and you use the Parameters.AddWithValue method to set the parameter values to what you have defined in the query string.
By the way, you should be using using statements to encapsulate some of your objects, here is what I typically do:
using (OleDbConnection conn = new OleDbConnection(_connStr))
using (OleDbCommand = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT ...";
cmd.Parameters.AddWithValue(...);
cmd.ExecuteReader();
//...
}
That way you don't have to worry about cleaning up resources if something goes wrong inside or closing the connection when you are done.
I am trying to connect to an oracle database using C#.
Here is my code:
OracleConnection conn = new OracleConnection(); // C#
conn.ConnectionString = oradb;
conn.Open();
string sql = " select department_name from departments where department_id = 10"; // C#
OracleCommand cmd = new OracleCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.CommandType = CommandType.Text; ///this is the line that gives the error
What is the proper way to set the command type? Thank you.
Using Store Procedure:
using (OracleConnection conn = new OracleConnection( oradb ))
{
conn.Open();
OracleCommand cmd = new OracleCommand("StoreProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
//specify command parameters
//and Direction
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//string s = reader.GetInt32(0) + ", " + reader.GetInt32(1);
}
}
}
CommandType.Text: (not mandatory to specify CommandType).
using (OracleConnection conn = new OracleConnection( oradb ))
{
string sql = #"SELECT department_name FROM departments
WHERE department_id = #department_id";
conn.Open();
OracleCommand cmd = new OracleCommand(sql, conn);
//specify command parameters
cmd.Parameters.Add(new OracleParameter("#department_id", 10));
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//string s = reader.GetString(0);
}
}
}
Make sure you toss each of these pieces in a using() statement, i.e.
using( OracleConnection conn = new OracleConnection( oradb ) )
{
conn.Open();
using( OracleCommand cmd = new OracleCommand( "sql here", conn ) )
{
//cmd.Execute(); cmd.ExecuteNonQuery();
}
}
I am trying to run a test query using sql. I know it is a simple concept, but i have tried everything I could find online and the following does not even run. It shows no errors but it does not run.
private static SqlConnection conn = new SqlConnection("<connection string>");
public static void connect()
{
conn.Open();
SqlCommand command = new SqlCommand("spTester 'this is tested'", conn);
command.ExecuteScalar();
conn.Close();
}
It seems that you want something like that:
private static void connect() {
// static SqlConnection conn is a bad idea, local variable is much better
// Do not forget to dispose IDisposable: using(...) {...}
using (SqlConnection conn = new SqlConnection("<connection string>")) {
// Do not forget to dispose IDisposable: using(...) {...}
using (SqlCommand command = new SqlCommand("spTester", conn)) {
// You're executing procedure, not ordinal SQL
command.CommandType = CommandType.StoredProcedure;
// It seems, that you should provide a parameter to your procedure:
//TODO: Change "#ParameterName" to actual one
command.Parameters.Add(new SqlParameter("#ParameterName", "this is tested"));
// You don't need any result value be returned
command.ExecuteNonQuery();
}
}
}
public static void connect()
{
conn.Open();
SqlCommand command = new SqlCommand("spTester 'this is tested'", conn);
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Close();
}
try doing this..
as u probably forgot to mention command.CommandType = CommandType.StoredProcedure; line
this is a simple example it will let you get started using SQLCOMMAND
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Try this :
public static void connect()
{
conn.Open();
SqlCommand command = new SqlCommand("spTester", conn);
command.CommandType = CommandType.StoredProcedure;
command.AddWithValue("#Parameter1","this is tested")
SqlDataAdapter da = new SqlDataAdapter(cmd);
conn.Close();
}
I have this code to execute a stored procedure (Update SP) in ASP.Net, unfortunately record is not updating when I run the code.
This is my code:
using (SqlConnection sqlConnection = Connt.GetConnection(TblName))
{
sqlConnection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(SqlScript, sqlConnection))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
adapter.SelectCommand.Parameters.AddRange(SqlParam);
}
}
Where SqlScript is the variable for the stored procedure name and SqlParam is the parameters.
Please help me figure out what is wrong with my code.
Hi you can try something like this
SqlConnection sqlConnection = new SqlConnection();
SqlCommand sqlCommand = new SqlCommand();
sqlConnection.ConnectionString = "Data Source=SERVERNAME;Initial Catalog=DATABASENAME;Integrated Security=True";
public void samplefunct(params object[] adparam)
{
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.CommandText = "SPName";
sqlCommand.Parameters.Add("#param1", SqlDbType.VarChar).Value = adparam[0];
sqlCommand.Parameters.Add("#param2", SqlDbType.VarChar).Value = adparam[1];
sqlCommand.Parameters.Add("#Param3", SqlDbType.VarChar).Value = adparam[2];
sqlCommand.ExecuteNonQuery();
}
Try:
using (var conn = new SqlConnection(connectionString))
using (var command = new SqlCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
With a Param:
command.Parameters.Add(new SqlParameter("#ID", 123));