資源簡介
C#通過ODBC鏈接SQLServer數據庫
代碼片段和文件信息
using?System;
using?System.Collections.Generic;
using?System.Data;
using?System.Data.Odbc;
using?System.Linq;
using?System.Text;
using?System.Threading.Tasks;
namespace?ODBC
{
????class?Program
????{
????????static?void?Main(string[]?args)
????????{
????????????Console.WriteLine(“請輸入鏈接字符串“);
????????????string?config?=?Console.ReadLine();
????????????Connect(config);
????????????Console.ReadLine();
????????}
????????public?static?void?Connect(string?config)
????????{
????????????try
????????????{
????????????????//DSN:mylink數據源的名稱?UID:sql?server登錄時的身份sa?PWD:登錄時的密碼123456
????????????????//生成連接數據庫字符串
????????????????if?(String.IsNullOrEmpty(config))
????????????????{
????????????????????config?=?“server=localhost;DSN=SQL_SERVER;UID=COMOSUSER;PWD=******“;
????????????????}
????????????????//定義SqlConnection對象實例
????????????????OdbcConnection?connection?=?new?OdbcConnection(config);
????????????????string?sql?=?“select?name?from?sysobjects?where?xtype=‘U‘“;
????????????????OdbcDataAdapter?odbcAdapter?=?new?OdbcDataAdapter(sql?connection);
????????????????DataSet?result?=?new?DataSet();
????????????????odbcAdapter.Fill(result);
????????????????foreach?(DataTable?dataTable?in?result.Tables)???//遍歷所有的datatable
????????????????{
????????????????????foreach?(DataRow?dataRow?in?dataTable.Rows)???///遍歷所有的行
????????????????????????foreach?(DataColumn?dataColumn?in?dataTable.Columns)???//遍歷所有的列
????????????????????????????Console.WriteLine(“{0}{1}{2}“?dataTable.TableName?dataColumn.ColumnName?dataRow[dataColumn]);
????????????????????//表名列名單元格數據
????????????????}
????????????}
????????????catch?(System.Exception?e)
????????????{
????????????????Console.WriteLine(e.ToString());
????????????}
????????}
????}
}
評論
共有 條評論