在Visual Studio2019中使用C#语言连接Sql Server数据库

发布时间 2023-09-23 20:27:57作者: yesyes1

1、首先在visual studio里面创建好自己的表

服务资源管理器-->连接数据库:

然后选择sql server数据库文件,并自定义数据库名称,显示不存在点击创建即可;

2、创建自己的程序对应的字段的表

3、连接数据库操作

1、引入连接数据库需要使用的using关键字

2、编写Connection代码语句

这里面需要写连接字符串,它在这里获取:
右键数据库名称,选择属性:

在右下角可以看到这样的一行数据:

将内容复制到上面的双引号里面去:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace BookStore
{
    public partial class Books : Form
    {
        public Books()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        private void label8_Click(object sender, EventArgs e)
        {

        }

        SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\12140\Documents\BookStore.mdf;Integrated Security=True;Connect Timeout=30");
        private void BSave_Click(object sender, EventArgs e)
        {
            
        }
    }
}

其他的增删改查语句自己写就行了。