zoukankan      html  css  js  c++  java
  • 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(); 

  • 相关阅读:
    通用网络管理方案归纳
    visual studio 中将选中代码相同的代码的颜色设置,修改高亮颜色
    (转)git stash使用
    (转) git--Remote远程仓库的使用
    (转)git checkout 撤销修改
    (转)git中关于fetch的使用
    (转)Visual Studio控制台程序输出窗口一闪而过的解决方法
    (转)sublime text3简体中文版汉化教程
    git使用记录
    (转)Java 中正确使用 hashCode 和 equals 方法
  • 原文地址:https://www.cnblogs.com/joma/p/2675602.html
Copyright © 2011-2022 走看看