2019年9月20日

MySQL、MSSQL 連線方式及如何使用DataTable取得資料 for C#


    using MySql.Data.MySqlClient;
    using System.Data;


    DataTable dt = new DataTable();
    MySqlConnection conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MISConnection"].ConnectionString);
    conn.Open();

          using (MySqlCommand cmd = new MySqlCommand())
          {
               string CmdText = @"select * from basic where PK=@PK";

               cmd.Parameters.AddWithValue("@PK", PK);
               cmd.Connection = conn;
               cmd.CommandText = CmdText;
               
               MySqlDataReader myData = cmd.ExecuteReader();

               if (myData.HasRows)
               {
                    dt.Load(myData);
               }
          }

    conn.Close();

      
      using System.Data;
      using System.Data.SqlClient;

      SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnStr"].ConnectionString);
      cn.Open();
      String PK = "1";
      DataTable dt = new DataTable();
 
      string _sql = @"select * from basic where PK=@PK";
      using (SqlCommand cmd = new SqlCommand(_sql, cn))
      {
           cmd.Parameters.Clear();
           cmd.Parameters.AddWithValue("@PK", PK);
           //cmd.ExecuteNonQuery();
           using (SqlDataAdapter da = new SqlDataAdapter(cmd))
           {
               dt.BeginLoadData();
               da.Fill(dt);
           }

      }
        
        cn.Close();

沒有留言:

張貼留言