// 設計連接數據庫的字符串方法
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();
}