SqlConnection 資料庫連線

1 篇文章 / 0 new
author
SqlConnection 資料庫連線
public partial class Form1 : Form
{
    private SqlConnection objConn;
    public Form1()
    {
        InitializeComponent();
        string sConnectionString = "Password=user; User ID=netuser;"
            + "Initial Catalog=pubs; Data Source=192.168.0.200\\SQLEXPRESS;";
        objConn = new SqlConnection(sConnectionString);
        objConn.Open();
    }
 
    private void button1_Click(object sender, EventArgs e)
    {
        string sql = "Select * From Authors";
        //建立 DataAdapter
        //SqlCommand cmd = new SqlCommand(sql, objConn);
        //SqlDataAdapter daAuthors = new SqlDataAdapter(cmd);
        SqlDataAdapter da = new SqlDataAdapter(sql, objConn);
 
        //自動產生 insert,update,delete 的sql語法
        //update,delete 自動產生的sql語句效率並不佳, 最好還是自行使用 SqlCommand 撰寫執行
        SqlCommandBuilder cb = new SqlCommandBuilder(da);//若無需異動則不需要
        addLine("Insert");
        addLine(cb.GetInsertCommand().CommandText);
        addLine(Environment.NewLine + "Update");
        addLine(cb.GetUpdateCommand().CommandText);
        addLine(Environment.NewLine + "Delete");
        addLine(cb.GetDeleteCommand().CommandText);
 
        //從 Authors table 取出資料
        useDataSet(da, objConn.Database);
        //useDataTable(daAuthors, "Authors");
    }
    private void useDataSet(SqlDataAdapter da, string idName)
    {
        DataSet ds = new DataSet(idName);//idName非一定要,註記用途,匯出xml之root標記
        da.FillSchema(ds, SchemaType.Source, "Authors");//僅填schema不含資料
        da.Fill(ds, "Authors");
        //給 DataSet,必須再指定 table name
        this.dataGridView1.DataSource = ds;
        this.dataGridView1.DataMember = "Authors";
        //this.dataGridView1.DataSource = ds.Tables["Authors"];//直接給 DataTable
    }
    private void useDataTable(SqlDataAdapter da, string idName)
        {//使用 DataTable
        DataTable dt = new DataTable(idName);//idName非一定要,註記 TableName
        da.Fill(dt);
        this.dataGridView1.DataSource = dt;
        //MessageBox.Show(dt.TableName);
    }
 
    private void Form1_FormClosed(object sender, FormClosedEventArgs e)
    {
        objConn.Close();
    }
    private void addLine(string data)
    {
        this.richTextBox1.AppendText(data + Environment.NewLine);
    }
}
Free Web Hosting