數據庫鏈接

private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection Conn = new SqlConnection("Server=192.168.2.10;Database=Fly;uid=sa;pwd=***");
            Conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO [Fly].[dbo].[A](ID,ID_Name)VALUES('E','E項目')";
            cmd.Connection = Conn;
            cmd.ExecuteNonQuery();//這個僅僅執行SQL命令,不返回結果集,實用於建表、批量更新
            Conn.Close(); // 關閉數據庫鏈接
        }
                //------------------------------------------------------------------------------------------------------------------------------
                        private void button2_Click(object sender, EventArgs e)
        {
            String connsql = "Server=192.168.2.10;Database=Fly;uid=sa;pwd=***"; // 數據庫鏈接字符串,database設置爲本身的數據庫名,以Windows身份驗證
            try
            {
                using (SqlConnection conn = new SqlConnection())
                {
                    conn.ConnectionString = connsql;
                    conn.Open(); // 打開數據庫鏈接
                    String sql = "select * from Fly..A"; // 查詢語句
                    SqlDataAdapter myda = new SqlDataAdapter(sql, conn); // 實例化適配器
                    DataTable dt = new DataTable(); // 實例化數據表
                    myda.Fill(dt); // 保存數據  
                    dataGridView1.DataSource = dt; // 設置到DataGridView中
                    conn.Close(); // 關閉數據庫鏈接
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("錯誤信息:" + ex.Message, "出現錯誤");
            }
        }
相關文章
相關標籤/搜索