VS2013 c#连接Sql Server2008数据库并访问数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38877910/article/details/87187345

连接这个数据库花了我一天半的时间,写下这篇作为备忘也为了方便其他遇到这方面的问题的人

我使用的环境是vs2013,数据库是SQL Sever 2008

1,创建数据表格,这个可能纯小白很难看懂https://jingyan.baidu.com/article/a3f121e4cf554efc9152bb4e.html

2,连接数据库 https://blog.csdn.net/meiqizao/article/details/78151479?locationNum=6&fps=1

连接数据库成功后,在“服务器资源管理”处选中数据库,然后可以在“属性”窗口找到“连接字符串”,复制其内容,赋给MySqlCon

3,访问数据库,将第二步中“连接字符串”复制得到的内容给到代码这一句

myconnection = new SqlConnection("Data Source=FUSHENGQING;Initial Catalog=mydbew;Integrated Security=True;")

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 WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        SqlConnection myconnection;
        private void button1_Click(object sender, EventArgs e)
        {
             try
              {
                  myconnection = new SqlConnection("Data Source=FUSHENGQING;Initial Catalog=mydbew;Integrated Security=True;");
                  myconnection.Open();     //打开数据库
                  label1.Text = "数据库连接成功!";
              }
              catch (Exception ee)
              {
                  MessageBox.Show("数据库连接失败!" + ee.ToString());
              }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
              {
                  string SQL = "select * From my";  // 搜索语句 http://www.w3school.com.cn/sql/sql_select.asp
                  SqlDataAdapter objDataAdpter = new SqlDataAdapter();
                  objDataAdpter.SelectCommand = new SqlCommand(SQL, myconnection);
                  DataSet ds = new DataSet();
                  objDataAdpter.Fill(ds, "my");
                  dataGridView1.DataSource = ds.Tables[0];//搜索语句 https://jingyan.baidu.com/article/1709ad80a318c44635c4f041.html
              }
 
            catch (Exception ee)
             {
                  MessageBox.Show("查询失败!" + ee.ToString());
              }
        }
    }
}

这是我从纯小白自己慢慢摸索的,网上虽然也有一些资料,可能都不是很系统,我把自己初学的查找思路写成了这篇博文,如果大家有什么不懂的也请加我qq446073886共同探讨,大神轻喷,这篇的讲解也不错https://blog.csdn.net/kiss__soul/article/details/80316788

猜你喜欢

转载自blog.csdn.net/weixin_38877910/article/details/87187345
今日推荐