数据库连接,ACCESS,SQL.

1.ACCESS 连接

View Code
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 连接

View Code
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);
}

}
}
}



posted on 2012-04-05 13:28  明哥哥 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/momin808/archive/2012/04/05/2433028.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值