【C#】ADO.NET 常用資料存取用法

程式碼(Sample):

using System.Data;                     //使用ADO.NET,引用命名空間
using System.Data.SqlClient;    //使用ADO.NET,引用命名空間

//(方法一)連接SQL Server資料庫檔案
//constr連接字串指定連接dbStudent.mdf資料庫
  string constr = @"Data Source=(LocalDB)\MSSQLLocalDB;" +
                              "AttachDbFilename=|DataDirectory|dbStudent.mdf;" +
                              "Integrated Security=True";
 
 //(方法二)連接SQL Server資料庫來源
 //使用SqlClient進行SQL Server驗證

  //string constr = @"Server=localhost;Database=Student;uid=sa_test;pwd=test1234;Persist Security Info=False";
 
 //使用SqlClient進行Windows驗證
 //string constr = @"Server=localhost;Database=Student;Persist Security Info=False;Trusted_Connection=True"
 
  //上述constr連接字串方法依情況擇一使用(標示藍色依實際狀況調整,本篇只是示意)


  //executeSql方法可傳入SQL字串來輯編資料表
  private void executeSql(string sql)
  {

      SqlConnection con = new SqlConnection();
      con.ConnectionString = constr;
      con.Open();
      SqlCommand cmd = new SqlCommand(sql, con);
      cmd.ExecuteNonQuery();
      con.Close();
  }

  //querySql方法可傳入SQL字串並傳回DataTable物件
  private DataTable querySql(string sql)
  {

      SqlConnection con = new SqlConnection();
      con.ConnectionString = constr;
      SqlDataAdapter adp = new SqlDataAdapter(sql, con);
      DataSet ds = new DataSet();
      adp.Fill(ds);
      return ds.Tables[0];
  }
  
  // GET: Home
  public ActionResult Index()
  {

      DataTable dt = querySql("SELECT * FROM tStudent");
      return View(dt);
  }

  // POST: Home/Create
  [HttpPost]
  public ActionResult Create(string fStuId, string fName, string fEmail, int fScore)
  {

      string sql = "INSERT INTO tStudent(fStuId,fName,fEmail,fScore)VALUES('"
          + fStuId.Replace("'", "''") + "',N'"
          + fName.Replace("'", "''") + "','"
          + fEmail.Replace("'", "''") + "',"
          + fScore + ")";
      executeSql(sql);
      return RedirectToAction("Index");
  }

  // GET: Home/Delete/id
  public ActionResult Delete(string id)
  {

      string sql = "DELETE FROM tStudent WHERE fStuId='"
          + id.Replace("'", "''") + "'";
      executeSql(sql);
      DataTable dt = querySql("SELECT * FROM tStudent");
      return RedirectToAction("Index");
  }

留言

這個網誌中的熱門文章

【ASP】日期轉換(西元<-->民國)

【VB】使用NPOI元件來匯出Excel--DataTableToExcel

【SQL】符號切割字串變成多欄