I have a method which contains a very big sql query directly in the .CS file. What would the recommended refactoring method be?
You could put the large complex SQL query into a SQL View or Stored Procedure, and just use that in the code.
You should use stored procedure
string commandText = "SP_Your_Sp_Name";
using (SqlConnection objSqlConnection = Connection)
{
using (SqlCommand cmd = new SqlCommand(commandText, objSqlConnection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Parameter_Name", value));
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
result = (string)cmd.ExecuteScalar();
}
}
Use a stored procedure.
In this case the query execution will be faster when the execution plan is stored in the cache.
Related
In VB.net I can simply execute a stored procedure in SQL Server 2008 using the query in image below, but in C# I got an error.
Can you help me about the proper syntax in C#?
Thanks
using (SqlConnection conn = new SqlConnection(your-connection-string)) {
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("your-procedure-name", 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("#Username", textBox1.Text));
cmd.Parameters.Add(new SqlParameter("#Password", textBox2.Text));
// execute the command
using (SqlDataReader result = cmd.ExecuteReader()) {
// iterate through results, printing each to console
while (result .Read())
{
// Name and Password Should Match with your proc col name
var userName = result["Name"].toString();
var password = result["password"].toString();
}
}
}
For More details Please Read this this
How to execute a stored procedure within C# program
Problem statement.
Basically I get 3 - 50 parameters that come back from a web service as a NVP array I then need to loop over them create the SQL command parameters for each and call the stored procedure. Is there a more efficient way to handle it than the approach below?
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand cm = connection.CreateCommand())
{
cm.CommandText = "MySproc";
cm.CommandType = CommandType.StoredProcedure;
foreach (var field in row)
{
cm.Parameters.AddWithValue("#" + field.Key.ToString(), field.Value.ToString());
}
cm.ExecuteNonQuery();
}
}
I personally use the ISNULL or COALESCE in the WHERE clause of the stored procedure. Unless your looking to do it inside your c#...
http://blogs.x2line.com/al/archive/2004/03/01/189.aspx
kindly let me know how to insert two variables. its not a problem giving directly my userid and mobile in the code like
string insert =#"Insert into userHistory(userid,mobile) values(x,y)";
This is my code, but it fails to insert (editors note: OP provided no error)
int userid = 123456;
long mobile = 91888888888;
sqlConn = new MySqlConnection(/* conn string removed */);
sqlConn.Open();
string insert =
#"Insert into userHistory(userid,mobile) values(#userid,#mobile);";
MySqlCommand cmd = new MySqlCommand(insert,sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new MySqlParameter("#userid", userid));
cmd.Parameters.Add(new MySqlParameter("#mobile", mobile));
Without more Information, I guess the type of your command should be "Text" and not CommandType.StoredProcedure, since you do not execute a SP. And you have to execute the command (maybe this is only missing in your code)
this is wrong cmd.CommandType = CommandType.StoredProcedure the command is should be CommandType.Text
You can read more about the CommandType enumeration here.
There are some more .net examples for MySql here
I think the issue is cmd.CommandType = CommandType.StoredProcedure;
You are trying to execute an ad-hoc query, not a Stored Procedure. Try changing it to
cmd.CommandType = CommandType.Text;
Is this code safe from SQL injections? Why?
public void AddPlayer(string username)
{
var query = "INSERT INTO dbo.Player(Username, RegisterDate) VALUES(#Username, #RegisterDate)";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#Username", username);
command.Parameters.AddWithValue("#RegisterDate", DateTime.Now);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
public DateTime GetRegisterDate(string username)
{
var query = "SELECT RegisterDate FROM dbo.Player WHERE Username = #Username";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#Username", username);
command.Connection.Open();
return (DateTime)command.ExecuteScalar();
}
}
EDIT: Could injection-safe equivalent code be written using a stored procedure? If so, what the stored procedure would be like?
Yes, It looks safe.
Because it uses parameters.
You run a risk of SQL-injection when you create queries like
baseQueryText + " WHERE Username =" + TextBox.Text;
Reguarding the Edit: When you use a Stored Procedure you always use parameters so they are safe too. No special effort required, but you still could/should filter incoming data.
Yes. You are using parameterized queries, which are in general considered safe from SQL injection.
You may still want to consider filtering your inputs anyway.
Yes, all the non-static data is being fed in via bound parameters.
I have a procedure, I want to read schema of the procedure. To retrieve view schema I use the query shown here. Same way I want to get schema of stored procedure. How to get it? Plz show some syntax.
public static DataTable SchemaReader(string tableName)
{
string sql = string.Format("Select * from {0}", tableName);
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
If have any query plz ask.Thanks in advance.
you could do
public static DataTable SchemaReader(string tableName)
{
string sql = "MySP";//replace this with your store procedure name
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = cmd.ExecuteReader();
DataTable schema = reader.GetSchemaTable();
reader.Close();
conn.Close();
return schema;
}
Hope this help
This is an answer that does not call the SP - if you do, you may inadvertently affect data:
SELECT * FROM sys.dm_exec_describe_first_result_set ('owner.sprocName', NULL, 0) ;
This returns the result set :
is_hidden
column_ordinal
name
is_nullable
system_type_id
system_type_name
max_length
precision
scale
collation_name
user_type_id
user_type_database
user_type_schema
user_type_name
assembly_qualified_type_name
xml_collection_id
xml_collection_database
xml_collection_schema
xml_collection_name
is_xml_document
is_case_sensitive
is_fixed_length_clr_type
source_server
source_database
source_schema
source_table
source_column
is_identity_column
is_part_of_unique_key
is_updateable
is_computed_column
is_sparse_column_set
ordinal_in_order_by_list
order_by_is_descending
order_by_list_length
error_number
error_severity
error_state
error_message
error_type
error_type_desc
You could get information about a stored procedure's parameters but, without executing it, SQL Server cannot tell you the structure of the dataset(s) returned by the stored procedure. Since executing a stored procedure can have side effects, ADO.NET doesn't provide a method for telling you what the result set(s) would look like were the stored procedure to be executed. Furthermore, the result set(s) might change depending on the parameters passed to the procedure when it is executed.
I am not getting your question clearly I think this would work with you
Select *
from sys.objects
where type='p' and name = (procedure name)
Replace your query with this and it will work fine
I've created various code generators that use the output of stored procs. In my experience, most procedures that SELECT anything output their schema just the same if you call them with null (DbNull.Value) as the value for all parameters. You can get the parameter list itself from system views, though I find it convenient to use INFORMATION_SCHEMA.PARAMETERS.
By executing the procedure in a transaction and always rolling back you can safely execute stuff even when you have no idea what the procedure does.
You'll probably need a basic GUI and allow the user to modify the parameters - or a config file or some other way to provide parameter values for specific procedures. A stored proc may produce output with different schemas depending on the parameters, though I haven't seen many that do.
App.config
<appSettings>
<add key="Schema_Name" value ="[dev]."/> <!-- use any one [dev]. or [dbo]. -->
</appSettings>
c# read Key
string schema_Name = Configuration["Schema_Name"].ToString();
Store Procedure
SqlConnection objConn = new SqlConnection(Connection);
objConn.Open();
SqlCommand cmd = new SqlCommand("Exec WLTCVarification", objConn);
cmd.Parameters.Add("#SchemaName", SqlDbType.Text);
cmd.Parameters["#Schema_Name"].Value = schema_Name; // dev or dbo;
rowsAmount = (string)cmd.ExecuteScalar();
objConn.Close();
c# Sql Query
SqlConnection objConn = new SqlConnection(Connection);
objConn.Open();
SqlCommand cmd = new SqlCommand("select * from " + schema_Name + "receive_agv_onlyerror, objConn);
rowsAmount = (string)cmd.ExecuteScalar();
objConn.Close();