1.ADO对象连接数据库
创建一个MFC对话框工程
StdAfx.h中添加#import "c:/program files/common files/system/ado/msado15.dll" no_namespace rename ("EOF", "adoEOF") rename ("BOF", "adoBOF")
CADOApp类中添加public数据成员 _ConnectionPtr m_pConnection; _RecordsetPtr m_set;
初始化函数BOOL CADOApp::InitInstance()中添加
::CoInitialize(NULL);
CString strSQL;
HRESULT hr;
try
{
hr=m_pConnection.CreateInstance(__uuidof(Connection));
m_pConnection->CursorLocation=adUseClient;
strSQL="Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=cap;Data Source=AI";
if(SUCCEEDED(hr))
{
hr=m_pConnection->Open(_bstr_t(strSQL),"","",-1);
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
errormessage.Format("连接数据库失败!/r/n错误信息:%s",e.ErrorMessage());
AfxMessageBox(errormessage);///显示错误信息
return FALSE;
}
身份验证模式为:"sql server和windows"
Provider=SQLOLEDB.1;Persist Security Info=True;User ID=用户名;Password=密码;Initial Catalog=数据库名;Data Source=SQL服务器名
身份验证模式为:"仅windows"
Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=数据库名;Data Source=SQL服务器名
2.ADO.NET连接数据库
创建一个c#控制台程序
使用命名空间using System.Data.OleDb;(该名空间可以连接各种数据源)
编写连接字符串
windows身份验证:
"Persist Security Info=False;Integrated Security=SSPI;
database=AdventureWorks;server=(local)"
sql登陆:
"Persist Security Info=False;User ID=*****;Password=*****;Initial Catalog=AdventureWorks;Server=MySqlServer"
database=数据库名称 Server=服务器名称 (local)意为本地服务器
创建连接
string connectionString;
connectionString = "Provider=SQLOLEDB;Persist Security Info=False;Integrated Security=SSPI;Server=(local);Database=cap";
using (OleDbConnection connection =new OleDbConnection(connectionString))
{
try
{
connection.Open();
connection.Close();
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}