Aquí es un simple tutorial limitada:
En primer lugar, desea tenga una clase para hacer el trabajo duro por usted, luego la usará con facilidad.
Primero, debe encajar la cadena de conexión en su archivo web.config y asígnele un nombre. Aquí se llama DatabaseConnectionString
, pero puede llamarlo myCS
según se requiera en la pregunta.
Ahora, en App_Code crear un nuevo archivo de clase y el nombre de SqlComm
(esto es sólo un ejemplo de nombre) como:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
public class SqlComm
{
// this is a shortcut for your connection string
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConStr"].ConnectionString;
// this is for just executing sql command with no value to return
public static void SqlExecute(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// with this you will be able to return a value
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
// with this you can retrieve an entire table or part of it
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
// sooner or later you will probably use stored procedures.
// you can use this in order to execute a stored procedure with 1 parameter
// it will work for returning a value or just executing with no returns
public static object SqlStoredProcedure1Param(string StoredProcedure, string PrmName1, object Param1)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(PrmName1, Param1.ToString()));
cmd.Connection.Open();
object obj = new object();
obj = cmd.ExecuteScalar();
return obj;
}
}
}
bien, esto sólo una clase, y ahora usted debe saber cómo usarlo :
Si se desea ejecutar un comando como borrar, insertar, actualizar, etc. utilizar este:
SqlComm.SqlExecute("TRUNCATE TABLE Table1");
pero si usted necesita para recuperar un valor específico del uso de bases de datos º es decir:
int myRequiredScalar = 0;
object obj = new object();
obj = SqlComm.SqlReturn("SELECT TOP 1 Col1 FROM Table1");
if (obj != null) myRequiredScalar = (int)obj;
Puede recuperar un montón de filas de la base de datos de esta manera (otros como otras formas) Esto es relevante a su pregunta sepecific
int Col1Value = 0;
DataTable dt = new DataTable();
dt = SqlComm.SqlDataTable("SELECT * FROM myTable WHERE myPK='simpleText'");
if (dt.Rows.Count == 0)
{
// do something if the query return no rows
// you may insert the relevant redirection you asked for
}
else
{
// Get the value of Col1 in the 3rd row (0 is the first row)
Col1Value = (int)dt.Rows[2]["Col1"];
// or just make the other redirection from your question
}
Si necesita ejecutar un procedimiento almacenado con o sin devolver un valor de nuevo esta es la manera de hacerlo (en este ejemplo hay ningún valor de regresar)
SqlComm.SqlStoredProcedure1Param("TheStoredProcedureName", "TheParameterName", TheParameterValue);
una vez más, para su ret pregunta específica urn la tabla usando el SqlDataTable
, y redirigir si dt.Rows.Count >0
Diviértete.
¿Qué es PjSql.dbcs()? Esto debería ser cambiado. –
+1 - Admiro específicamente cómo se creó una clase independiente para la ejecución de comandos sql para la organización y la coherencia – Abob