C#连接数据库的几种方法总结

针对各种不同的连接字符串请查看:http://www.connectionstrings.com(绝对地符合我们开发需求)

 

1、连接SQL SERVER数据库方法:

导入命名空间:using System.Data.SqlClient;

连接数据库代码:

string connectString = @"Data Source=.\mssqlserver2008; Initial Catalog=WinFormAppDemo; Uid=sa; Pwd=***"; //数据库管理员模式登录

string connectString2 = @"Data Source=.\mssqlserver2008; Initial Catalog=WinFormAppDemo; Integrated Security=true"; //操作系统身份验证登录

SqlConnection baseConnection = new SqlConnection(connectString2);

try

{

baseConnection.Open();

MessageBox.Show("Connect Successfully!");

}

catch (SqlException sql)

{

MessageBox.Show(sql.Message);

throw sql;

}

2、 连接Access数据库方法:

导入命名空间:using System.Data.OleDb

连接数据库代码:

string connectString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\VSproj\Database31.mdb ; "; //03版Access连接字符串

string connectString2 = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\VSproj\Database31.accdb ; "; //07、12版Access连接字符串

OleDbConnection myConnection = new OleDbConnection(connectString2);

try

{

myConnection.Open();

MessageBox.Show("Connect Successfully!");

}

catch (OleDbException ole)

{

MessageBox.Show(ole.Message);

throw ole;

}

 3、连接Excel作为数据源方法:

导入命名空间:(同Access)using System.Data.OleDb

连接Excel代码:

string excelConnection = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\VSproj\09.xls; Extended Properties='Excel 8.0'"; //03版excel驱动程序  

string excelConnection2 = @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=D:\VSproj\09.xls; Extended Properties='Excel 12.0'"; //07,10版excel驱动程序

OleDbConnection excelConnect = new OleDbConnection(excelConnection);

try

{

excelConnect.Open();

MessageBox.Show("Connect Successfully!");

}

catch (OleDbException ole)

{

MessageBox.Show(ole.Message);

throw;

}

finally

{

  excelConnect.Close(); 

 

 

 

 

转载于:https://www.cnblogs.com/joma/archive/2012/09/07/2675602.html

你可能感兴趣的:(C#连接数据库的几种方法总结)