1.ACCESS 连接
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace OleDbConnectionTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
//新建连接对象conn
OleDbConnection conn = new OleDbConnection();
//构造数据库连接字符串
//必须使用Server.MapPath方法将相对路径转化为服务器
//上的绝对路径
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
connStr += @"Data\Student.mdb";
//输出目前的连接字符串,查看Server.MapPath的作用
MessageBox.Show("当前连接字符串为:\n" + connStr + "\n");
//指定conn对象的连接字符串属性
conn.ConnectionString = connStr;
conn.Open();
//测试是否打开连接
if (conn.State == ConnectionState.Open)
{
MessageBox.Show("成功打开数据库连接");
}
//关闭连接
conn.Close();
//测试是否关闭连接
if (conn.State == ConnectionState.Closed)
{
MessageBox.Show("成功关闭数据库连接");
}
}
//捕获异常
catch (Exception ex)
{
MessageBox.Show("数据库连接失败,可能的原因是:\n" + ex.Message);
}
}
}
}
2.SQL 连接
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace SqlConnectionTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=(local);user id=sa;password=1234;initial catalog=students;";
conn.Open();
if(conn.State == ConnectionState.Open)
{
MessageBox.Show("连接已经打开");
}
conn.Close();
if(conn.State == ConnectionState.Closed)
{
MessageBox.Show("连接已经关闭");
}
}
catch(Exception ex)
{
MessageBox.Show("数据库连接失败,可能的原因是" + ex.Message);
}
}
}
}