C# - Buat Koneksi visual C# ke SQL Server 2008, Dengan Store Procedur Tanpa Parameter

Koneksi visual C# ke SQL Server 2008, Dengan Store Procedur Tanpa Parameter
Code #1 :




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Inventory_Sport
{
    public class koneksi
    {
        SqlConnection con;
        SqlCommand cmd;
        SqlDataAdapter da;

        public koneksi ()
        {
            this.con = new SqlConnection(@"uid=sa;pwd=u_password;initial
 catalog=Inventory;data source=.");
        }
        public DataTable execQueryProc(string sql)
        {
            this.con.Open();
            this.cmd = new SqlCommand();
            this.cmd.Connection = this.con;

            try
            {
                this.cmd.CommandType = CommandType.StoredProcedure;
                this.cmd.CommandText = sql;

                this.da = new SqlDataAdapter(this.cmd);

                DataTable dt = new DataTable("data");
                this.da.Fill(dt);
                return dt;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                this.cmd.Dispose();
                this.cmd = null;
                if (this.con.State == ConnectionState.Open)
                    this.con.Close();
            }
        }
 }//end class
}

dan cara memanggil perintah diatas di class berbeda
Code #2 :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Inventory_Sport
{
    public partial class Fkategori : Form
    {
        DataTable dtKategori;
        koneksi db = new koneksi();

        public Fkategori()
        {
            InitializeComponent();
        }
        private void Fkategori_Load(object sender, EventArgs e)
        {
            this.dtKategori = this.db.execQueryProc("viewKategori");
            Dgv.DataSource = dtKategori;
            Dgv.Refresh();
        }
    }
}


No comments:

Post a Comment