2012-03-21 41 views
9

這是一個有經驗的初學者提出的問題!如何用c#代碼創建sql連接,訪問sql server然後有條件地重定向?

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

我在web.config中的連接字符串MYDATABASE名爲 「myCS」。 我有一個名爲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"); 
} 

回答

20

這裏是一個有限的簡單教程:

首先,你要有一堂課爲你做了辛苦的工作,那麼你會很輕鬆地使用它。

首先,您必須在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; 

您可以從數據庫中檢索了一堆行的這種方式(其他類似其他方式) 這是有關您的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 
} 

如果您需要執行一個存儲過程有或沒有返回值回報,這是要做到這一點(在這個例子中有沒有返回值)的方式

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

再次,對於您的具體問題RET使用SqlDataTable的表格,並重定向如果dt.Rows.Count >0

玩得開心。

+0

什麼是PjSql.dbcs()?這應該改變。 – 2013-07-26 14:44:20

+0

+1 - 我特別佩服你如何爲組織和一致性執行sql命令創建一個獨立的類 – Abob 2017-03-10 04:02:02

2

方法有很多種:LINQSqlDataReaderSQLDataAdapter,根據你想讀(單值,數據表...)什麼,所以這裏有一個例子:

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