c#連接數據庫的幾種方法


// 設計連接數據庫的字符串方法 

using System.Data.SqlClient;

使用sqlConnectionStringBuilder類

  SqlConnectionStringBuilder  sc = new  SqlConnectionStringBuilder  ();

    sc.DataSource = " " ; 數據庫地址

    sc.UersID = " "; 數據庫登錄名

    sc.Password = ""; // 登錄密碼
    sc.InitialCatalog = ""; //數據庫

 sc.ConnectionString = sc.ToString();

// 開始連接

  //SqlConnection connection = new SqlConnection(sc.ConnectionString))

using (SqlConnection connection = new SqlConnection(strSql2))    //SqlConnection connection = new SqlConnection(sc.toString))
{
connection.Open();
if (connection.State == System.Data.ConnectionState.Open) {
Console.WriteLine("連接成功");
}

// 連接數據庫表
SqlCommand comm = new SqlCommand("select * from class",connection); // 數據庫的連接
// comm.ExecuteNonQuery(); // 適用於增刪改 執行SQL 並返回受影響的行數

SqlDataReader reader = comm.ExecuteReader(); // 適用於查


while (reader.Read())
{
Console.WriteLine(String.Format("班級:{0}年級:{1}", reader[0], reader[1]));

}
Console.ReadLine();

 

// 使用oDBC

 

// ODBC 方式

//連接字符串
string connect = "DSN=lgbb;uid=sa;Pwd=123";
using (OdbcConnection odconnection = new OdbcConnection(connect))
{
odconnection.Open();
if (odconnection.State == System.Data.ConnectionState.Open)
{
Console.WriteLine("連接成功");
}

  如果使用的odbc 連接方式

  查詢的時候使用odbcCommand comm = new odbcCommand()
Console.ReadLine();
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM