ADO.NET---VS2013连接自带的数据库---ShinePans

2015-07-24 09:23:05 · 作者: · 浏览: 1

1.新建项目(console or winform)

\

2.添加组件,选择数据库文件

\

自己名一个名字,我选择的是test1.mdf

3.打开数据库,右键选择属性

\

4.获得连接字符串

\

5.连接成功

\

6.关闭连接

\


至此,本地的数据库连接已经成功测试了.



代码:

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

namespace adoStep_one
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //连接字符串,通过打开mdf文件,然后查看属性获得连接字符串
            //这一点是非常方便的
             string connectionString="Data Source=(LocalDB)\\v11.0;AttachDbFilename=E:\\编程开发\\dotNET\\ADO.NET\\demo\\连接数据库\\adoStep_one\\adoStep_one\\test1.mdf;Integrated Security=True";
            //访问数据库的类
             SqlConnection conn = new SqlConnection(connectionString);
            //与数据库建立连接
            try
            {
                conn.Open();
                MessageBox.Show("已建立与数据库的连接!");
            }
             catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            conn.Dispose();
            MessageBox.Show("已断开与数据库的连接");
            
        }
    }
}