VS連接SQL server數(shù)據(jù)庫(kù)及實(shí)現(xiàn)基本CRUD操作
目錄
- 連接數(shù)據(jù)庫(kù)
- 使用dataGridView控件顯示表中的數(shù)據(jù)。
- 實(shí)現(xiàn)基本CRUD操作
- 總結(jié)
連接數(shù)據(jù)庫(kù)
打開vs,點(diǎn)擊 視圖,打開sql資源管理器,添加SQL Server
輸入服務(wù)器名稱,用戶名,密碼,進(jìn)行連接。
如圖,就可以看到vs已經(jīng)連接到了自己的數(shù)據(jù)庫(kù),class和song兩個(gè)數(shù)據(jù)庫(kù) 。可以看到class下面有五個(gè)表。
查看其中一個(gè)SC表,數(shù)據(jù)顯示正常,證明已連接。
使用dataGridView控件顯示表中的數(shù)據(jù)。
在工具箱中找到dataGridView控件拖入Form1中,如圖:
下面進(jìn)行底層代碼編寫
using System.Data;using System.Data.SqlClient;namespace connect_sql{ public partial class Form1 : Form {public Form1(){ InitializeComponent(); Table();} //數(shù)據(jù)寫入,公共的,所有有表格的地方都用的上 public void Table() { SqlConnection sqlcon = new SqlConnection(); sqlcon.ConnectionString = "Data Source=LAPTOP-HIAIVLQI;Initial Catalog=class;Integrated Security=True"; sqlcon.Open(); dataGridView1.Rows.Clear(); string sql = "select * from sc"; SqlCommand com = new SqlCommand(sql, sqlcon); SqlDataAdapter ada = new SqlDataAdapter(sql, sqlcon);//建立SQL語(yǔ)句與數(shù)據(jù)庫(kù)的連接 DataSet ds = new DataSet(); //實(shí)例化Datatable類 ada.Fill(ds); //添加SQL并且執(zhí)行 dataGridView1.DataSource = ds.Tables[0].DefaultView;//顯示數(shù)據(jù) } }}
運(yùn)行程序,F(xiàn)orm1窗體中已通過dataGridView顯示數(shù)據(jù),且數(shù)據(jù)與源數(shù)據(jù)無誤。
實(shí)現(xiàn)基本CRUD操作
創(chuàng)建people表格,打開sql資源管理器,鼠標(biāo)右鍵點(diǎn)擊對(duì)應(yīng)數(shù)據(jù)庫(kù)下的表,添加新表如下;
填寫相關(guān)sql語(yǔ)句,進(jìn)行建表。
插入以下兩條數(shù)據(jù):
通過dataGridView顯示數(shù)據(jù),正常,插入成功。
后續(xù)的CRUD操作不再贅述,都可通過下列代碼嵌入SQL語(yǔ)句進(jìn)行使用。
public void Table() { SqlConnection sqlcon = new SqlConnection(); sqlcon.ConnectionString = "Data Source=LAPTOP-HIAIVLQI;Initial Catalog=song;Integrated Security=True";//連接服務(wù)器 sqlcon.Open(); dataGridView1.Rows.Clear(); string sql = "select * from people";//SQL語(yǔ)句,可自己編寫需要的。 SqlCommand com = new SqlCommand(sql, sqlcon); SqlDataAdapter ada = new SqlDataAdapter(sql, sqlcon);//建立SQL語(yǔ)句與數(shù)據(jù)庫(kù)的連接 DataSet ds = new DataSet(); //實(shí)例化Datatable類 ada.Fill(ds); //添加SQL并且執(zhí)行 dataGridView1.DataSource = ds.Tables[0].DefaultView;//顯示數(shù)據(jù) }
那么以上就是VS連接SQL Server 數(shù)據(jù)庫(kù)一些基本操作。
如需了解具體代碼,可轉(zhuǎn)至我的gitee倉(cāng)庫(kù)查詢:
總結(jié)
到此這篇關(guān)于VS連接SQL server數(shù)據(jù)庫(kù)及實(shí)現(xiàn)基本CRUD操作的文章就介紹到這了,更多相關(guān)VS連接SQL server數(shù)據(jù)庫(kù)內(nèi)容請(qǐng)搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
