VS连接SQL server数据库及实现基本CRUD操作

连接数据库

打开vs,点击 视图,打开sql资源管理器,添加SQL Server

输入服务器名称,用户名,密码,进行连接。

如图,就可以看到vs已经连接到了自己的数据库,class和song两个数据库 。可以看到class下面有五个表。

查看其中一个SC表,数据显示正常,证明已连接。

使用dataGridView控件显示表中的数据。

在工具箱中找到dataGridView控件拖入Form1中,如图:

下面进行底层代码编写

using System.Data;
using System.Data.SqlClient;
namespace connect_sql
{
 public partial class Form1 : Form
 {
 public Form1()
 {
 InitializeComponent();
	Table();
 }
	//数据写入,公共的,所有有表格的地方都用的上
	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语句与数据库的连接
	DataSet ds = new DataSet(); //实例化Datatable类
	ada.Fill(ds); //添加SQL并且执行 
	dataGridView1.DataSource = ds.Tables[0].DefaultView;//显示数据 
	}
 
	}
}

 运行程序,Form1窗体中已通过dataGridView显示数据,且数据与源数据无误。

实现基本CRUD操作

创建people表格,打开sql资源管理器,鼠标右键点击对应数据库下的表,添加新表如下;

填写相关sql语句,进行建表。

插入以下两条数据:

 通过dataGridView显示数据,正常,插入成功。

 后续的CRUD操作不再赘述,都可通过下列代码嵌入SQL语句进行使用。

public void Table()
	{
	SqlConnection sqlcon = new SqlConnection();
	sqlcon.ConnectionString = "Data Source=LAPTOP-HIAIVLQI;Initial Catalog=song;Integrated Security=True";//连接服务器
	sqlcon.Open();
	dataGridView1.Rows.Clear();
	string sql = "select * from people";//SQL语句,可自己编写需要的。
	SqlCommand com = new SqlCommand(sql, sqlcon); 
	SqlDataAdapter ada = new SqlDataAdapter(sql, sqlcon);//建立SQL语句与数据库的连接
	DataSet ds = new DataSet(); //实例化Datatable类
	ada.Fill(ds); //添加SQL并且执行 
	dataGridView1.DataSource = ds.Tables[0].DefaultView;//显示数据 
	}

那么以上就是VS连接SQL Server 数据库一些基本操作。

如需了解具体代码,可转至我的gitee仓库查询:

https://gitee.com/song-77/vs-connection-sql-server

总结

作者:song.22原文地址:https://blog.csdn.net/qq_54074534/article/details/124979794

%s 个评论

要回复文章请先登录注册