C# - Koneksi Visual C# ke Database SQL SERVER 2008 dengan SqlCommand Query

Koneksi Visual C# ke Database SQL SERVER 2008 dengan SqlCommand Query

contoh listing program #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 execSQL(string sql)
        {
            this.con.Open();
            this.cmd = new SqlCommand();
            this.cmd.Connection = this.con;

            try
            {
                this.cmd.CommandType = CommandType.Text;
                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
}

cara pemanggilan class tersebut
listing program #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.execSQL("select * from kategori");
            Dgv.DataSource = dtKategori;
            Dgv.Refresh();
        }
    }
}

Good Luck

3 comments:

  1. Gan, kalo saya mau koneksiin 2 database bagaimana ya? Jadi ada komputer A dengan database 'A' dan ada komputer B dengan database 'B'. Sewaktu2 komputer A mengirim request data ke komputer B. Lalu komputer B membalas dengan mengirim kembali data yang diinginkan komputer A.

    ReplyDelete
    Replies
    1. Kalo koneksi tetap sama, soalnya koneksi kan cuma baca value database, kalo mau melempar data dari A ke B, ya ditambahkan fungsi lagi

      Delete