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("已断开与数据库的连接");
}
}
}
时间: 2024-08-24 22:03:11