大家好,今天的教學是如何使用讀取內建的localDB中的資料。
Step 1. 首先先點擊資料庫,接著找到連線字串,並且複製
Step 2.打開Web.config檔案,輸入底下的程式碼,檔案讀取連接字串
<connectionStrings>
<add name="connect" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\black\source\repos\ithome\ithome\App_Data\Database1.mdf;Integrated Security=True" />
</connectionStrings>
Step 3. 在HomeController ,輸入以下的程式碼
public ActionResult Demo()
{
return View();
}
Step 4-1. 建立View,對著Controller按下右鍵
Step 4-2. 按下加入
Step 4-3. 成功建立View的畫面
Step 5-1. using 要使用的類別
using System.Configuration;
using System.Data.SqlClient;
Step 5-2. 在Controller加入
string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
Step 6. 建立資料
Step 7. 寫Function 撈資料
public string[] GetData()
{
string[] arr = { "", "", ""};
using (SqlConnection conn = new SqlConnection(strConnString))
{
conn.Open();
SqlCommand scom = new SqlCommand("", conn);
scom.CommandText = @"
select
id,
name,
age
from [dbo].[people]
";
SqlDataReader sread = scom.ExecuteReader();
if (sread.Read())
{
arr[0] = sread["id"].ToString();
arr[1] = sread["name"].ToString();
arr[2] = sread["age"].ToString();
}
}
return arr;
}
Step 8. 撈出資料後,傳到View
public ActionResult Demo()
{
string[] array = GetData();
ViewBag.id = array[0];
ViewBag.name = array[1];
ViewBag.age = array[2];
return View();
}
Step 9. View
@{
ViewBag.Title = "Demo";
}
<h2>Demo</h2>
@ViewBag.id
@ViewBag.name
@ViewBag.age
Step 10. 成功畫面
稍微改了一下:
public List<string> GetData(string strConnString, string CommandText)
{
List<string> rowList = new List<string>();
using (SqlConnection conn = new SqlConnection(strConnString))
{
conn.Open();
SqlCommand scom = new SqlCommand("", conn);
scom.CommandText = CommandText;
SqlDataReader sread = scom.ExecuteReader();
if (sread.Read())
{
for (int i = 0; i < sread.FieldCount; i++)
{
rowList.Add(sread[i].ToString());
}
}
}
return rowList;
}
public ActionResult Demo()
{
string strConnString = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
string queryString = "Select ID,NAME,AGE FROM[DBO].[PEOPLE]";
List<string> resList = GetData(strConnString, queryString);
ViewBag.ID = resList[0];
ViewBag.NAME = resList[1];
ViewBag.AGE = resList[2];
return View();
}
感謝分享