程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C# ADO.NET操作數據代碼匯總(1)

C# ADO.NET操作數據代碼匯總(1)

編輯:關於C語言

一.用SqlConnection連接SQL Server

1..加入命名空間

using System.Data.SqlClIEnt;

2.連接數據庫

SqlConnection myConnection = new SqlConnection();

myConnection.ConnectionString = "user id=sa;passWord=sinofindb;initial catalog=test;data source=127.0.0.1;Connect Timeout=30";

myConnection.Open();

改進(更通用)的方法:

string MySQLConnection="user id=sa;passWord=sinofindb;Database =test;data source=127.0.0.1;Connect Timeout=30";

SqlConnection myConnection = new SqlConnection(MySQLConnection);

myConnection.Open();

二、用OleDbConnection連接

1.加入命名空間

using System.Data.OleDb;

2.連接SQL Server

string MySQLConnection="Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=test;Integrated Security=SSPI;";

SqlConnection myConnection = new SqlConnection(MySQLConnection);

myConnection.Open();

3.連接Access(可通過建立.udl文件獲得字符串)

string MySQLConnection="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\db2000.mdb;

Persist Security Info=False;

4.連接Oracle(也可通過OracleConnection連接)

string MySQLConnection="Provider=MSDAORA;Data Source=db; user id=sa;passWord=sinofindb";

三.創建Command對象

1.SqlCommand 構造函數

①初始化 SqlCommand 類的新實例。public SqlCommand();

SqlCommand myCommand = new SqlCommand();

②初始化具有查詢文本的 SqlCommand 類的新實例。public SqlCommand(string);

String mySelectQuery = "SELECT * FROM mindata";

SqlCommand myCommand = new SqlCommand(mySelectQuery);

③初始化具有查詢文本和 SqlConnection 的SqlCommand類實例。

Public SqlCommand(string, SqlConnection);

String mySelectQuery = "SELECT * FROM mindata";

string myConnectString = "user id=sa;passWord=;database=test;server=MySQLServer";

SqlConnection myConnection = new SqlConnection(myConnectString);

SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);

④初始化具有查詢文本、SqlConnection 和 Transaction 的 SqlCommand 類實例。

public SqlCommand(string, SqlConnection, SqlTransaction);

SqlTransaction myTrans = myConnection.BeginTransaction();

String mySelectQuery = "SELECT * FROM mindata";

string myConnectString = "user id=sa;passWord=;database=test;server=MySQLServer";

SqlConnection myConnection = new SqlConnection(myConnectString);

SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection, myTrans);

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved