aspnet資料庫教程
Data Source=localhost;Initial Catalog=cdshop;Integrated Security=True
loacalhost 是你要訪問的數據源地址
可填
. 或者 localhost 代表本機 (.\sqlexpress 代表sqlserver2005的本機)
機器名 或者IP地址 就是遠程伺服器了
cdshop改成你的資料庫名就可以了.
㈡ asp.net連接資料庫實例
Sub LoadCommandList()
Dim objConn As New Odbc.OdbcConnection
Dim objCmd As New Odbc.OdbcCommand
Dim objDataReader As Odbc.OdbcDataReader
CommandList.Items.Clear()
objConn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb)};Dbq=" & Application.StartupPath & "\database.mdb"
Debug.Print(Application.StartupPath & "\database.mdb")
objConn.Open()'連接資料庫
objCmd.Connection = objConn
objCmd.CommandText = "select * from Commands"
objDataReader = objCmd.ExecuteReader()'執行SQL語句
While objDataReader.Read()'讀數據,以下和資料庫連接無關
CommandList.Items.Add(objDataReader.GetString(0) & "," & objDataReader.GetString(1))
End While
objConn.Close()
End Sub
二
Asp.net連接SQL Server2000資料庫常式詳解:
<%@ Import Namespace="System.Data" %>
<%@ Import NameSpace="System.Data.SqlClient" %>
<script laguage="VB" runat="server">
sub page_load(sender as Object,e as EventArgs)
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim ds as DataSet
'1.連接資料庫
myConnection = New SqlConnection( "server=localhost;database=Pubs;uid=ueytjdf;pwd=doekdf" )
myConnection.Open()
la1.text="Connection Opened!"
'2.建立一個新表
myCommand = New SqlCommand( "CREATE TABLE [test] ([id] [int] IDENTITY (1, 1) NOT NULL ,[name] [char] (10) COLLATE Chinese_PRC_CI_AS NULL ,[sex] [char] (10) COLLATE Chinese_PRC_CI_AS NULL )", myConnection )
myCommand.ExecuteNonQuery()
la2.text="New table created!"
'2 添加紀錄
myCommand = New SqlCommand( "Insert into [test] (name,sex) values( '黃志文','男' )", myConnection )
myCommand.ExecuteNonQuery()
la3.text="New Record Inserted!"
'3 更新數據
myCommand = New SqlCommand( "UPDATE [test] SET name='Smith' where name='李明'", myConnection )
myCommand.ExecuteNonQuery()
la4.text="Record Updated!"
'4 刪除數據
myCommand = New SqlCommand( "delete from [test] where name='Smith'", myConnection )
myCommand.ExecuteNonQuery()
la5.text="Record Deleted!"
'5 用DataGrid顯示數據
myCommand = New SqlCommand( "select * from [test]", myConnection )
MyDataGrid.DataSource=myCommand.ExecuteReader()
MyDataGrid.DataBind()
end sub
</script>
<html>
<body>
<asp:label id="la1" runat="server" /><br>
<asp:label id="la2" runat="server" /><br>
<asp:label id="la3" runat="server" /><br>
<asp:label id="la4" runat="server" /><br>
<asp:label id="la5" runat="server" /><br>
<ASP:DataGrid id="MyDataGrid" runat="server"
BorderColor="black"
BorderWidth="1"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
Font-Name="Verdana"
Font-Size="10pt"
HeaderStyle-BackColor="#aaaadd"
AlternatingItemStyle-BackColor="#eeeeee"
>
</asp:DataGrid>
</body>
</html>
----------------------------------------------------------------------------------------------------
ASP.net連接access資料庫常式
<%@ Import Namespace="System.Data" %>
<%@ Import NameSpace="System.Data.OleDb" %>
<script laguage="VB" runat="server">
Dim myConnection As OleDbConnection
Dim myCommand As OleDbCommand
sub page_load(sender as Object,e as EventArgs)
'1.連接資料庫
dim dbname as string
dbname=server.mappath("authors.mdb")
myConnection = New OleDbConnection( "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA Source="&dbname )
myConnection.Open()
la1.text="Connection Opened!"
'2.添加記錄
myCommand = New OleDbCommand( "Insert INTO Authors(Authors,country) Values('Simson','usa')", myConnection )
myCommand.ExecuteNonQuery()
la2.text="New Record Inserted!"
'3 更新數據(Access)
myCommand = New OleDbCommand( "UPDATE Authors SET Authors='Bennett' WHERE Authors = 'Simson'", myConnection )
myCommand.ExecuteNonQuery()
la3.text="Record Updated!"
'4 刪除數據(access)
myCommand = New OleDbCommand( "DELETE FROM Authors WHERE Authors = 'David'", myConnection )
myCommand.ExecuteNonQuery()
la4.text="Record Deleted!"
'5 使用DateGrid顯示數據
myCommand = New OleDbCommand( "select * FROM Authors", myConnection )
MyDataGrid.DataSource=myCommand.Executereader()
MyDataGrid.DataBind()
end sub
</script>
<html>
<body>
<asp:label id="la1" runat="server" /><br>
<asp:label id="la2" runat="server" /><br>
<asp:label id="la3" runat="server" /><br>
<asp:label id="la4" runat="server" /><br>
<ASP:DataGrid id="MyDataGrid" runat="server"
BorderColor="black"
BorderWidth="1"
GridLines="Both"
CellPadding="3"
CellSpacing="0"
Font-Name="Verdana"
Font-Size="10pt"
HeaderStyle-BackColor="#aaaadd"
AlternatingItemStyle-BackColor="#eeeeee"
>
</asp:DataGrid>
</body>
</html>
1.C#連接連接Access
[復制此代碼]CODE:
using System.Data;
using System.Data.OleDb;
..
string strConnection="Provider=Microsoft.Jet.OleDb.4.0;";
strConnection+=@"Data Source=C:BegASPNETNorthwind.mdb";
OleDbConnection objConnection=new OleDbConnection(strConnection);
..
objConnection.Open();
objConnection.Close();
解釋:
連接Access資料庫需要導入額外的命名空間,所以有了最前面的兩條using命令,這是必不可少的!
strConnection這個變數里存放的是連接資料庫所需要的連接字元串,他指定了要使用的數據提供者和要使用的數據源.
"Provider=Microsoft.Jet.OleDb.4.0;"是指數據提供者,這里使用的是Microsoft Jet引擎,也就是Access中的數據引擎,asp.net就是靠這個和Access的資料庫連接的.
"Data Source=C:\BegASPNET\Northwind.mdb"是指明數據源的位置,他的標准形式是"Data Source=MyDrive:MyPath\MyFile.MDB".
PS:
1."+="後面的"@"符號是防止將後面字元串中的"\"解析為轉義字元.
2.如果要連接的資料庫文件和當前文件在同一個目錄下,還可以使用如下的方法連接:
strConnection+="Data Source=";
strConnection+=MapPath("Northwind.mdb");
這樣就可以省得你寫一大堆東西了!
3.要注意連接字元串中的參數之間要用分號來分隔.
"OleDbConnection objConnection=new OleDbConnection(strConnection);"這一句是利用定義好的連接字元串來建立了一個鏈接對象,以後對資料庫的操作我們都要和這個對象打交道.
"objConnection.Open();"這用來打開連接.至此,與Access資料庫的連接完成.
2.C#連接SQL Server
[復制此代碼]CODE:
using System.Data;
using System.Data.SqlClient;
..
string strConnection="user id=sa;password=;";
strConnection+="initial catalog=Northwind;Server=YourSQLServer;";
strConnection+="Connect Timeout=30";
SqlConnection objConnection=new SqlConnection(strConnection);
..
objConnection.Open();
objConnection.Close();
解釋:
連接SQL Server資料庫的機制與連接Access的機制沒有什麼太大的區別,只是改變了Connection對象和連接字元串中的不同參數.
首先,連接SQL Server使用的命名空間不是"System.Data.OleDb",而是"System.Data.SqlClient".
其次就是他的連接字元串了,我們一個一個參數來介紹(注意:參數間用分號分隔):
"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=30":連接超時時間為30秒.
在這里,建立連接對象用的構造函數為:SqlConnection.
3.C#連接Oracle
[復制此代碼]CODE:
using System.Data.OracleClient;
using System.Data;
//在窗體上添加一個按鈕,叫Button1,雙擊Button1,輸入以下代碼
private void Button1_Click(object sender, System.EventArgs e)
{
string ConnectionString="Data Source=sky;user=system;password=manager;";//寫連接串
OracleConnection conn=new OracleConnection(ConnectionString);//創建一個新連接
try
{
conn.Open();
OracleCommand cmd=conn.CreateCommand();
cmd.CommandText="select * from MyTable";//在這兒寫sql語句
OracleDataReader odr=cmd.ExecuteReader();//創建一個OracleDateReader對象
while(odr.Read())//讀取數據,如果odr.Read()返回為false的話,就說明到記錄集的尾部了
{
Response.Write(odr.GetOracleString(1).ToString());//輸出欄位1,這個數是欄位索引,具體怎麼使用欄位名還有待研究
}
odr.Close();
}
catch(Exception ee)
{
Response.Write(ee.Message); //如果有錯誤,輸出錯誤信息
}
finally
{
conn.Close(); //關閉連接
}
}
4.C#連接MySQL
[復制此代碼]CODE:
using MySQLDriverCS;
// 建立資料庫連接
MySQLConnection DBConn;
DBConn = new MySQLConnection(new MySQLConnectionString("localhost","mysql","root","",3306).AsString);
DBConn.Open();
// 執行查詢語句
MySQLCommand DBComm;
DBComm = new MySQLCommand("select Host,User from user",DBConn);
// 讀取數據
MySQLDataReader DBReader = DBComm.ExecuteReaderEx();
// 顯示數據
try
{
while (DBReader.Read())
{
Console.WriteLine("Host = {0} and User = {1}", DBReader.GetString(0),DBReader.GetString(1));
}
}
finally
{
DBReader.Close();
DBConn.Close();
}
//關閉資料庫連接
DBConn.Close();
5.C#連接IBM DB2
[復制此代碼]CODE:
OleDbConnection1.Open();
//打開資料庫連接
OleDbDataAdapter1.Fill(dataSet1,"Address");
//將得來的數據填入dataSet
DataGrid1.DataBind();
//綁定數據
OleDbConnection1.Close();
//關閉連接
//增加資料庫數據
在Web Form上新增對應欄位數量個數的TextBox,及一個button,為該按鍵增加Click響應事件代碼如下:
[復制此代碼]CODE:
this.OleDbInsertCommand1.CommandText = "INSERTsintosADDRESS(NAME,
EMAIL, AGE, ADDRESS) VALUES
('"+TextBox1.Text+"','"+TextBox2.Text+"','"+TextBox3.Text+"','"+TextBox4.Text+"')";
OleDbInsertCommand1.Connection.Open();
//打開連接
OleDbInsertCommand1.ExecuteNonQuery();
//執行該SQL語句
OleDbInsertCommand1.Connection.Close();
//關閉連接
6.C#連接SyBase
(OleDb)
[復制此代碼]CODE:
Provider=Sybase.ASEOLEDBProvider.2;Initial Catalog=資料庫名;User ID=用戶名;Data Source=數據源;Extended Properties="";Server Name=ip地址;Network Protocol=Winsock;Server Port Address=5000;
㈢ aspnet 和 ajax教程
ajxa是一種介於頁面與邏輯代碼部分交互的一層,可以實現頁面局部刷新的效
果,就跟某些論壇發回復一樣,整個頁面是不動的,而我點提交以後,我剛發
的內容自動的上去了,局部的。當然大部分都是js跳轉提示發布成功,然後
回跳,這只是一個例子。很多時候,是來增加用戶體驗感的。至於教程,談不
上,假如你用JS的話,找個簡單點例子看就明白了,無非就是傳值,判斷,回
調處理的一個過程。
㈣ 資料庫中有幾萬條數據,怎樣使用aspnetpage分頁控制項結合資料庫分頁讀取呢
可以用存儲過程分頁
/*
函數名稱: GetRecordFromPage
函數功能: 獲取指定頁的數據
參數說明: @tblName 包含數據的表名
@fldName 關鍵欄位名
@PageSize 每頁記錄數
@PageIndex 要獲取的頁碼
@OrderType 排序類型, 0 - 升序, 1 - 降序
@strWhere 查詢條件 (注意: 不要加 where)
*/
CREATE PROCEDURE GetRecordFromPage
@tblName varchar(255), -- 表名
@fldName varchar(255), -- 欄位名
@PageSize int = 10, -- 頁尺寸
@PageIndex int = 1, -- 頁碼
@OrderType bit = 0, -- 設置排序類型, 非 0 值則降序
@strWhere varchar(2000) = '' -- 查詢條件 (注意: 不要加 where)
AS
declare @strSQL varchar(6000) -- 主語句
declare @strTmp varchar(1000) -- 臨時變數
declare @strOrder varchar(500) -- 排序類型
if @OrderType != 0
begin
set @strTmp = '<(select min'
set @strOrder = ' order by [' + @fldName + '] desc'
end
else
begin
set @strTmp = '>(select max'
set @strOrder = ' order by [' + @fldName +'] asc'
end
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + ']' + @strOrder + ') as tblTmp)'
+ @strOrder
if @strWhere != ''
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + '] where [' + @fldName + ']' + @strTmp + '(['
+ @fldName + ']) from (select top ' + str((@PageIndex-1)*@PageSize) + ' ['
+ @fldName + '] from [' + @tblName + '] where ' + @strWhere + ' '
+ @strOrder + ') as tblTmp) and ' + @strWhere + ' ' + @strOrder
if @PageIndex = 1
begin
set @strTmp = ''
if @strWhere != ''
set @strTmp = ' where (' + @strWhere + ')'
set @strSQL = 'select top ' + str(@PageSize) + ' * from ['
+ @tblName + ']' + @strTmp + ' ' + @strOrder
end
exec (@strSQL)
GO
㈤ ASP.NET連接資料庫有哪幾種方法
連接Access
首先看一個例子代碼片斷:
程序代碼:
--------------------------------------------------------------------------------
using
System.Data;
using
System.Data.OleDb;
......
string
strConnection="Provider=Microsoft.Jet.OleDb.4.0;";
strConnection+=@"Data
Source=C:\BegASPNET\Northwind.mdb";
OleDbConnection
objConnection=new
OleDbConnection(strConnection);
......
objConnection.Open();
objConnection.Close();
......
--------------------------------------------------------------------------------
解釋:
連接Access資料庫需要導入額外的命名空間,所以有了最前面的兩條using命令,這是必不可少的!
strConnection這個變數里存放的是連接資料庫所需要的連接字元串,他指定了要使用的數據提供者和要使用的數據源.
"Provider=Microsoft.Jet.OleDb.4.0;"是指數據提供者,這里使用的是Microsoft
Jet引擎,也就是Access中的數據引擎,asp.net就是靠這個和Access的資料庫連接的.
"Data
Source=C:\BegASPNET\Northwind.mdb"是指明數據源的位置,他的標准形式是"Data
Source=MyDrive:MyPath\MyFile.MDB".
ps:
1."+="後面的"@"符號是防止將後面字元串中的"\"解析為轉義字元.
2.如果要連接的資料庫文件和當前文件在同一個目錄下,還可以使用如下的方法連接:
strConnection+="Data
Source=";
strConnection+=MapPath("Northwind.mdb");
這樣就可以省得你寫一大堆東西了!
3.要注意連接字元串中的參數之間要用分號來分隔.
"OleDbConnection
objConnection=new
OleDbConnection(strConnection);"這一句是利用定義好的連接字元串來建立了一個鏈接對象,以後對資料庫的操作我們都要和這個對象打交道.
"objConnection.Open();"這用來打開連接.至此,與Access資料庫的連接完成.其餘操作(插入,刪除...)請參閱相關書籍
連接SQL
Server
例子代碼片斷:
程序代碼:
--------------------------------------------------------------------------------
using
System.Data;
using
System.Data.SqlClient;
...
string
strConnection="user
id=sa;password=;";
strConnection+="initial
catalog=Northwind;Server=YourSQLServer;";
strConnection+="Connect
Timeout=30";
SqlConnection
objConnection=new
SqlConnection(strConnection);
...
objConnection.Open();
objConnection.Close();
...
--------------------------------------------------------------------------------
解釋:
連接SQL
Server資料庫的機制與連接Access的機制沒有什麼太大的區別,只是改變了Connection對象和連接字元串中的不同參數.
首先,連接SQL
Server使用的命名空間不是"System.Data.OleDb",而是"System.Data.SqlClient".
其次就是他的連接字元串了,我們一個一個參數來介紹(注意:參數間用分號分隔):
"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=30":連接超時時間為30秒.
在這里,建立連接對象用的構造函數為:SqlConnection.
其餘的就和Access沒有什麼區別了!
㈥ ASP.NET與資料庫的連接問題
SQL Server 是本地還是遠程 遠程你檢查一下是否允許進行遠程連接
你嘗試禁用個性化服務,修改WebPartManager的屬性:Personalization -> Enabled 為 False
不行 你把上面代碼改下
<add name="LocalSqlServer" connectionString="Data Source=localhost;Initial Catalog=lecro;Persist Security Info=True;User ID=sa;Password="
providerName="System.Data.SqlClient" />
試一下
㈦ ASP怎麼連接SQL資料庫
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data.SqlClient;//注意需要添加此句
namespaceaspnet3
{
publicpartialclassdatatest:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
stringstrconn="server=localhost;uid=sa;pwd=longlt;database=School";
SqlConnectionconn=newSqlConnection(strconn);//創建連接
stringsql="select*fromstudents";
conn.Open();
SqlCommandcmd=newSqlCommand(sql,conn);//執行查詢
Response.Write("連接成功");
SqlDataReaderdr=cmd.ExecuteReader();//查詢結果
if(dr.Read())
{
//利用dr[索引]對資料庫表進行操作,dr[]返回object;
//可以用欄位做索引,也可用列號0,1..做索引
Response.Write(dr[0].ToString()+"<br>");
}
//this.Lab.Text="suc";
}
}
}
在上面的例子中,我們連接了一個sa下的School資料庫,並查詢了其中students欄位的內容。
連接資料庫分為三個步驟:先定義連接信息,再創建一個連接,最後打開連接
stringstrconn="server=localhost;uid=sa;pwd=longlt;database=School";//在這一段修改資料庫的信息
SqlConnectionconn=newSqlConnection(strconn);//創建連接
conn.Open();//打開連接