熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

asp.net 數據庫連接的方法

2022-06-13   來源: .NET編程 

  Sub LoadCommandList()
Dim objConn As New OdbcOdbcConnection
Dim objCmd As New OdbcOdbcCommand
Dim objDataReader As OdbcOdbcDataReader
CommandListItemsClear()
objConnConnectionString = "Driver={Microsoft Access Driver (*mdb)};Dbq=" & ApplicationStartupPath & "databasemdb"
DebugPrint(ApplicationStartupPath & "databasemdb")
objConnOpen()連接數據庫
objCmdConnection = objConn
objCmdCommandText = "select * from Commands"
objDataReader = objCmdExecuteReader()執行SQL語句
While objDataReaderRead()讀數據以下和數據庫連接無關
CommandListItemsAdd(objDataReaderGetString() & "" & objDataReaderGetString())
End While
objConnClose()
End Sub



Aspnet連接SQL Server數據庫例程詳解:
<%@ Import Namespace="SystemData" %>
<%@ Import NameSpace="SystemDataSqlClient" %>
<script laguage="VB" runat="server">
sub page_load(sender as Objecte as EventArgs)
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ds as DataSet
連接數據庫
myConnection = New SqlConnection( "server=localhost;database=Pubs;uid=ueytjdf;pwd=doekdf" )
myConnectionOpen()
latext="Connection Opened!"

建立一個新表
myCommand = New SqlCommand( "CREATE TABLE [test] ([id] [int] IDENTITY ( ) NOT NULL [name] [char] () COLLATE Chinese_PRC_CI_AS NULL [sex] [char] () COLLATE Chinese_PRC_CI_AS NULL )" myConnection )
myCommandExecuteNonQuery()
latext="New table created!"

添加紀錄
myCommand = New SqlCommand( "Insert into [test] (namesex) values( 黃志文 )" myConnection )
myCommandExecuteNonQuery()
latext="New Record Inserted!"

更新數據
myCommand = New SqlCommand( "UPDATE [test] SET name=Smith where name=李明" myConnection )
myCommandExecuteNonQuery()
latext="Record Updated!"

刪除數據
myCommand = New SqlCommand( "delete from [test] where name=Smith" myConnection )
myCommandExecuteNonQuery()
latext="Record Deleted!"

用DataGrid顯示數據
myCommand = New SqlCommand( "select * from [test]" myConnection )
MyDataGridDataSource=myCommandExecuteReader()
MyDataGridDataBind()
end sub
</script>
<html>
<body>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<ASP:DataGrid id="MyDataGrid" runat="server"
BorderColor="black"
BorderWidth=""
GridLines="Both"
CellPadding=""
CellSpacing=""
FontName="Verdana"
FontSize="pt"
HeaderStyleBackColor="#aaaadd"
AlternatingItemStyleBackColor="#eeeeee"
>
</asp:DataGrid>

</body>
</html>

ASPnet連接access數據庫例程
<%@ Import Namespace="SystemData" %>
<%@ Import NameSpace="SystemDataOleDb" %>
<script laguage="VB" runat="server">
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
sub page_load(sender as Objecte as EventArgs)
連接數據庫
dim dbname as string
dbname=servermappath("authorsmdb")
myConnection = New OleDbConnection( "PROVIDER=MicrosoftJetOLEDB;DATA Source="&dbname )
myConnectionOpen()
latext="Connection Opened!"

添加記錄
myCommand = New OleDbCommand( "Insert INTO Authors(Authorscountry) Values(Simsonusa)" myConnection )
myCommandExecuteNonQuery()
latext="New Record Inserted!"

更新數據(Access)
myCommand = New OleDbCommand( "UPDATE Authors SET Authors=Bennett WHERE Authors = Simson" myConnection )
myCommandExecuteNonQuery()
latext="Record Updated!"

刪除數據(access)
myCommand = New OleDbCommand( "DELETE FROM Authors WHERE Authors = David" myConnection )
myCommandExecuteNonQuery()
latext="Record Deleted!"

使用DateGrid顯示數據
myCommand = New OleDbCommand( "select * FROM Authors" myConnection )
MyDataGridDataSource=myCommandExecutereader()
MyDataGridDataBind()

end sub
</script>
<html>
<body>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<asp:label id="la" runat="server" /><br>
<ASP:DataGrid id="MyDataGrid" runat="server"
BorderColor="black"
BorderWidth=""
GridLines="Both"
CellPadding=""
CellSpacing=""
FontName="Verdana"
FontSize="pt"
HeaderStyleBackColor="#aaaadd"
AlternatingItemStyleBackColor="#eeeeee"
>
</asp:DataGrid>

</body>
</html>
C#連接連接Access
 

[復制此代碼]CODE:
using SystemData;
using SystemDataOleDb;

string strConnection="Provider=MicrosoftJetOleDb;";
strConnection+=@"Data Source=C:BegASPNETNorthwindmdb";
OleDbConnection objConnection=new OleDbConnection(strConnection);

objConnectionOpen();
objConnectionClose();

  
解釋:
 連接Access數據庫需要導入額外的命名空間所以有了最前面的兩條using命令這是必不可少的!
 strConnection這個變量裡存放的是連接數據庫所需要的連接字符串他指定了要使用的數據提供者和要使用的數據源
 "Provider=MicrosoftJetOleDb;"是指數據提供者這裡使用的是Microsoft Jet引擎也就是Access中的數據引擎aspnet就是靠這個和Access的數據庫連接的
 "Data Source=C:BegASPNETNorthwindmdb"是指明數據源的位置他的標准形式是"Data Source=MyDrive:MyPathMyFileMDB"
PS:
 "+="後面的"@"符號是防止將後面字符串中的""解析為轉義字符
 如果要連接的數據庫文件和當前文件在同一個目錄下還可以使用如下的方法連接:
  strConnection+="Data Source=";
  strConnection+=MapPath("Northwindmdb");
  這樣就可以省得你寫一大堆東西了!
 要注意連接字符串中的參數之間要用分號來分隔
 "OleDbConnection objConnection=new OleDbConnection(strConnection);"這一句是利用定義好的連接字符串來建立了一個鏈接對象以後對數據庫的操作我們都要和這個對象打交道
 "objConnectionOpen();"這用來打開連接至此與Access數據庫的連接完成
C#連接SQL Server

[復制此代碼]CODE:
using SystemData;
using SystemDataSqlClient;

string strConnection="user id=sa;password=;";
strConnection+="initial catalog=Northwind;Server=YourSQLServer;";
strConnection+="Connect Timeout=";
SqlConnection objConnection=new SqlConnection(strConnection);

objConnectionOpen();
objConnectionClose();

  
解釋:
連接SQL Server數據庫的機制與連接Access的機制沒有什麼太大的區別只是改變了Connection對象和連接字符串中的不同參數
首先連接SQL Server使用的命名空間不是"SystemDataOleDb"而是"SystemDataSqlClient"
其次就是他的連接字符串了我們一個一個參數來介紹(注意:參數間用分號分隔):
 "user id=sa":連接數據庫的驗證用戶名為sa他還有一個別名"uid"所以這句我們還可以寫成"uid=sa"
 "password=":連接數據庫的驗證密碼為空他的別名為"pwd"所以我們可以寫為"pwd="
  這裡注意你的SQL Server必須已經設置了需要用戶名和密碼來登錄否則不能用這樣的方式來登錄如果你的SQL Server設置為Windows登錄那麼在這裡就不需要使用"user id"和"password"這樣的方式來登錄而需要使用"Trusted_Connection=SSPI"來進行登錄
 "initial catalog=Northwind":使用的數據源為"Northwind"這個數據庫他的別名為"Database"本句可以寫成"Database=Northwind"
  "Server=YourSQLServer":使用名為"YourSQLServer"的服務器他的別名為"Data Source""Address""Addr"如果使用的是本地數據庫且定義了實例名則可以寫為"Server=(local)實例名";如果是遠程服務器則將"(local)"替換為遠程服務器的名稱或IP地址
 "Connect Timeout=":連接超時時間為
 在這裡建立連接對象用的構造函數為:SqlConnection
C#連接Oracle
 

[復制此代碼]CODE:
using SystemDataOracleClient;
using SystemData;
//在窗體上添加一個按鈕叫Button雙擊Button輸入以下代碼
private void Button_Click(object sender SystemEventArgs e)
{
string ConnectionString="Data Source=sky;user=system;password=manager;";//寫連接串
OracleConnection conn=new OracleConnection(ConnectionString);//創建一個新連接
try
{
connOpen();
OracleCommand cmd=connCreateCommand();
cmdCommandText="select * from MyTable";//在這兒寫sql語句
OracleDataReader odr=cmdExecuteReader();//創建一個OracleDateReader對象
while(odrRead())//讀取數據如果odrRead()返回為false的話就說明到記錄集的尾部了
{
ResponseWrite(odrGetOracleString()ToString());//輸出字段這個數是字段索引具體怎麼使用字段名還有待研究
}
odrClose();
}
catch(Exception ee)
{
ResponseWrite(eeMessage); //如果有錯誤輸出錯誤信息
}
finally
{
connClose(); //關閉連接
}
}

  
C#連接MySQL
 

[復制此代碼]CODE:
using MySQLDriverCS;
// 建立數據庫連接
MySQLConnection DBConn;
DBConn = new MySQLConnection(new MySQLConnectionString("localhost""mysql""root""")AsString);
DBConnOpen();
// 執行查詢語句
MySQLCommand DBComm;
DBComm = new MySQLCommand("select HostUser from user"DBConn);
// 讀取數據
MySQLDataReader DBReader = DBCommExecuteReaderEx();
// 顯示數據
try
{
while (DBReaderRead())
{
ConsoleWriteLine("Host = {} and User = {}" DBReaderGetString()DBReaderGetString());
}
}
finally
{
DBReaderClose();
DBConnClose();
}
//關閉數據庫連接
DBConnClose();

  
C#連接IBM DB

[復制此代碼]CODE:
OleDbConnectionOpen();
//打開數據庫連接
OleDbDataAdapterFill(dataSet"Address");
//將得來的數據填入dataSet
DataGridDataBind();
//綁定數據
OleDbConnectionClose();
//關閉連接
//增加數據庫數據

  
在Web Form上新增對應字段數量個數的TextBox及一個button為該按鍵增加Click響應事件代碼如下
 

[復制此代碼]CODE:
thisOleDbInsertCommandCommandText = "INSERTsintosADDRESS(NAME
EMAIL AGE ADDRESS) VALUES
("+TextBoxText+""+TextBoxText+""+TextBoxText+""+TextBoxText+")";
OleDbInsertCommandConnectionOpen();
//打開連接
OleDbInsertCommandExecuteNonQuery();
//執行該SQL語句
OleDbInsertCommandConnectionClose();
//關閉連接

  
C#連接SyBase
(OleDb)
 

[復制此代碼]CODE:
Provider=SybaseASEOLEDBProvider;Initial Catalog=數據庫名;User ID=用戶名;Data Source=數據源;Extended Properties="";Server Name=ip地址;Network Protocol=Winsock;Server Port Address=
From:http://tw.wingwit.com/Article/program/net/201311/14210.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.