如何使用c#代码创建sql连接,访问sql服务器,然后有条件地重定向

本文关键字:sql 然后 服务器 有条件 重定向 访问 连接 何使用 代码 创建 | 更新日期: 2023-09-27 18:28:36

这是一个经验丰富的初学者提出的问题!

使用ASP.NET 4 C#和SQL server,

我在web.config中有一个名为"myCS"的到myDatabase的连接字符串。我有一个名为myDB的数据库。我有一个名为myTable的表,其主键名为myPK

创建SQL连接需要哪些代码行(最少代码),然后从myTable中选择,其中myPK=="simpleText"

它可能包括:

sqlconnection conn = new sqlconnection(??? myCS)
string SQLcommand = select * from myDB.myTable where myPK==myTestString;
sqlCommand command = new SqlCommand(SQL,conn);
conn.Open();
booleanFlag = ????
conn.Close();
conn.Dispose();

然后

If ( theAnswer  != NULL )  // or (if flag)
{
Response.Redirect("Page1.aspx");
}
else
{
Response.Redirect("Page2.aspx");
}

如何使用c#代码创建sql连接,访问sql服务器,然后有条件地重定向

这里有一个有限的简单教程:

首先,你想有一个班为你做艰苦的工作,然后你会轻松地使用它。

首先,您必须将连接字符串装入web.config文件并命名。这里它被命名为DatabaseConnectionString,但您可以根据问题的需要将其命名为myCS

现在,在App_Code中创建一个新的类文件,并将其命名为SqlComm(这只是一个示例名称),如:

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;
        }
    }
}

好吧,这只是一个类,现在你应该知道如何使用它:

如果你想执行删除、插入、更新等命令,请使用以下命令:

SqlComm.SqlExecute("TRUNCATE TABLE Table1");

但是,如果您需要从数据库中检索特定值,请使用以下方法:

int myRequiredScalar = 0;
object obj = new object();
obj = SqlComm.SqlReturn("SELECT TOP 1 Col1 FROM Table1");
if (obj != null) myRequiredScalar = (int)obj;

您可以通过这种方式从数据库中检索一堆行(其他方式与其他方式类似)这与您的特定问题有关

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
}   

如果您需要执行一个存储过程,无论是否返回值,这就是执行存储过程的方法(在本例中没有返回值)

SqlComm.SqlStoredProcedure1Param("TheStoredProcedureName", "TheParameterName", TheParameterValue);

同样,对于您的特定问题,使用SqlDataTable返回表格,如果dt.Rows.Count >0 则重定向

玩得开心。

有很多方法:LINQ、SqlDataReader、SQLDataAdapter,根据您想要读取的内容(单个值、数据表…),因此这里有一个示例:

using (SqlConnection con = new SqlConnection("SomeConnectionString"))
{
  var cmd = new SqlCommand("select from myTable where myPK==N'"+ simpleText+ "'",con);
  cmd.Connection.Open();
  var sqlReader = cmd.ExecuteReader();
  while(sqlReader.Read())
  {
    //Fill some data like : string result = sqlReader("SomeFieldName");
  }
  sqlReader.Close();
  cmd.Connection.Close();
  cmd.Dispose();
}
相关文章: