ADO.net之2-串連資料庫成功---ShinePans,

來源:互聯網
上載者:User

ADO.net之2-串連資料庫成功---ShinePans,
資料庫的配置:

連接字串:server=潘尚\\SQLEXPRESS;database=db_test;Trusted_Connection=true


串連代碼:

using System;using System.Collections.Generic;using System.Data.SqlClient;using System.Linq;using System.Text;using System.Threading.Tasks;namespace SQLTest{    class Program    {        static void Main(string[] args)        {            //串連資料庫            string connection =                "server=潘尚\\SQLEXPRESS;database=db_test;Trusted_Connection=true";            SqlConnection sc = new SqlConnection();            sc.ConnectionString = connection;            try            {                sc.Open();                Console.WriteLine("已經開啟資料庫連接!");            }            catch (Exception ex)            {                Console.WriteLine("開啟資料庫錯誤:{0}", ex.Message);            }            finally            {                sc.Close();                Console.WriteLine("資料庫連接已關閉!");            }            System.Console.ReadLine();        }    }}

串連結果:




adonet串連sql server資料庫問題

給你們簡單的寫個兩行代碼吧using System.Data;
using System.Data.SqlClient;//引入命名空間

public class DataLayer
{
private static SqlConnection CreateSqlConnection()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "server=218.28.188.237;uid=zhiagng;pwd=******;database=zhigang";
return conn;
}
}

在需調用這個串連的時候,可以直接引用類的靜態方法就行了:不要忘記開啟哦……
寫個案例:在一個網頁中擷取表A1資料:

SqlConnection _myConn = DataLayer.CreateSqlConnection();
_myConn.Open()://開啟資料庫連接
SqlCommand _QueryCmd = new SqlCommand();
_QueryCmd.Connection=_myConn;
_QueryCmd.CommandText="Select * from A1";
SqlDataAdapter _adpt= new SqlDataAdapter(_QueryCmd):
DataSet _ds = new DataSet();
_adpt.Fill(_ds,"A1"); //這樣DataSet對象就得到了資料

引用資料的時候可以這樣:

DataView1.DataSource=_ds.Tables[0];
DataView.DataBind();//綁定資料

以上可以使用單例模式進行簡寫,更容易一些!
 
ADONET 串連資料庫的問題

應該是關鍵字衝突
對錶命名最好不要用像user,name等等常見的單詞,我過去用name命了個表名,結果一直都有錯,最後才發現是命名的問題。
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.