小屋創作

日誌2024-04-22 15:51

C# MongoDB Atlas 雲端資料庫建置與教學

作者:貓貓風 ฅ●ω●ฅ

.





















Step1: 先到MongoDB Atlas首頁進行註冊與登入

進入網址


Step2 註冊完成後 登入 MongoDB Atlas  紅框處 Sign In

輸入帳密, 輸入完成後按 Login


Step3 建立專案名稱

Step4: 建立群集,選擇免費的即可



Step5: Database Access 建立存取帳號


Step6: NetWork Access 建立連線 IP

如果要任意IP都可連線輸入 0.0.0.0


Step7: 在 Connect選擇連線方式


因為我是用 Api連線所以選擇第一個 Driver


我是使用 C# 進行連線, 然後 Driver版本選2.1.3 或更新


接著獲取連線字串,這個要記下來
後面程式連線DB會用到

都設定完成後按右下角完成

Step8: 建立資料庫與表格


建立表格   輸入名稱
Addition Preference選擇 Clustered Index Collection
這樣每生成一筆資料都會產生一個不重複的ID做為資料的主鍵


Ste9: 開啟 Visual Studio 2019 ~2022或更新版本
            專案選擇 .Netframework 6.0或以上

         下載並安裝 MongoDB Api




Ste10: 完成設定,可以開始進行軟體開發了

//========== 程式碼 =======================

  1. using Amazon.Runtime.Internal;
  2. using MongoDB.Bson;
  3. using MongoDB.Bson.Serialization.Attributes;
  4. using MongoDB.Driver;
  5. using RestSharp;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.Net;
  10. using System.Net.Http.Json;
  11. using System.Net.Sockets;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Xml.Linq;
  15. using static MongoDB.Driver.WriteConcern;
  16. namespace MongoDB_online
  17. {
  18.     public partial class Form1 : Form
  19.     {
  20.         public Form1()
  21.         {
  22.             InitializeComponent();
  23.         }
  24.         char _double_quotes = (char)34;
  25.         MongoClient _client;
  26.         private bool connect_db()
  27.         {
  28.             bool connect_ok = false;
  29.             const string connectionUri = "mongodb+srv://你的連接字串";
  30.             var settings = MongoClientSettings.FromConnectionString(connectionUri);
  31.             settings.ServerApi = new ServerApi(ServerApiVersion.V1);
  32.             _client = new MongoClient(settings);
  33.             try
  34.             {
  35.                 var result = _client.GetDatabase("admin").RunCommand<BsonDocument>
  36.                (new BsonDocument("ping", 1));
  37.                 Console.WriteLine("Pinged your deployment. You successfully connected to
  38.                 MongoDB!");
  39.                 connect_ok = true;
  40.                 return connect_ok;
  41.             }
  42.             catch (Exception ex)
  43.             {
  44.                 Console.WriteLine(ex);
  45.                 connect_ok = false;
  46.                 return connect_ok;
  47.             }
  48.         }
  49.         private void Form1_Load(object sender, EventArgs e)
  50.         {
  51.             _IP_str = get_IP2();
  52.             if (connect_db())
  53.             {
  54.                 list_all_data();
  55.             }
  56.             else
  57.             {
  58.                 MessageBox.Show("Connect Error");
  59.             }
  60.         }
  61.         private System.Data.DataTable _tb;
  62.         DataRow _NewRow;
  63.         public async void list_all_data()
  64.         {
  65.             _tb = new System.Data.DataTable("table");
  66.             _tb.Clear(); //清空表格
  67.             _tb.Rows.Clear();//清空資料
  68.             _tb.Columns.Clear();
  69.             _tb.AcceptChanges();
  70.             dataGridView1.DataSource = null; //清除數據來源
  71.             dataGridView1.DefaultCellStyle.Font = new Font("Verdana", 11,
  72.             FontStyle.Bold);
  73.             dataGridView1.AllowUserToAddRows = false;
  74.             dataGridView1.AutoSizeColumnsMode =
  75.             DataGridViewAutoSizeColumnsMode.AllCells;
  76.             dataGridView1.DataSource = _tb;
  77.             var database = _client.GetDatabase("Test");
  78.             var collection = database.GetCollection<BsonDocument>("Activity");
  79.             var LS = await collection.Find(new BsonDocument()).ToListAsync();
  80.             List<String> fild_name = new List<string>();
  81.             fild_name.Clear();
  82.             fild_name = LS[0].Names.ToList();
  83.             for (int i = 0; i < fild_name.Count; i++)
  84.             {
  85.                 DataColumn colItem = new DataColumn(fild_name[i],
  86.                 Type.GetType("System.String"));
  87.                 _tb.Columns.Add(colItem);
  88.             }
  89.             for (int i = 0; i < LS.Count; i++)
  90.             {
  91.                 _NewRow = _tb.NewRow();
  92.                 for (int j = 0; j < fild_name.Count; j++)
  93.                 {
  94.                     _NewRow[fild_name[j]] = LS[i].GetValue(fild_name[j]);
  95.                 }
  96.                 _tb.Rows.Add(_NewRow);
  97.             }
  98.         }
  99.         private void insert_data(String MB, String CPU, String GPU)
  100.         {
  101.             var database = _client.GetDatabase("Test");
  102.             var collection = database.GetCollection<BsonDocument>("Activity");
  103.             collection.InsertOne(new BsonDocument
  104.                 {
  105.                     { "IP", "192.168.1.1" },
  106.                     { "UserName", "Name" },
  107.                     { "Time", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss") },
  108.                     { "MB", MB },
  109.                     { "CPU", CPU },
  110.                     { "GPU", GPU },
  111.                     { "storage1", "S1" },
  112.                     { "storage2", "S2" },
  113.                     { "storage3", "S3" },
  114.                     { "storage4", "S4" },
  115.                     { "storage5", "S5" },
  116.                     { "storage6", "S6" },
  117.                 });
  118.         }
  119.         private void button1_Click(object sender, EventArgs e)
  120.         {
  121.             insert_data(txt_MB.Text, txt_CPU.Text, txt_GPU.Text);
  122.             list_all_data();
  123.         }
  124.         static String _IP_str = "";
  125.         private String get_IP2() // 取得內網 IP
  126.         {
  127.             var host = Dns.GetHostEntry(Dns.GetHostName());
  128.             foreach (var ip in host.AddressList)
  129.             {
  130.                 if (ip.AddressFamily == AddressFamily.InterNetwork)
  131.                 {
  132.                     _IP_str = ip.ToString();
  133.                     //Console.WriteLine("IP Address = " + ip.ToString());
  134.                 }
  135.             }
  136.             return _IP_str;
  137.         }
  138.         /// <summary>
  139.         /// 取得外網 IP Address
  140.         /// </summary>
  141.         /// <returns></returns>
  142.         private String get_IP() //取得外網IP
  143.         {
  144.             String ip = "";
  145.             try
  146.             {
  147.                 using (var webClient = new WebClient())
  148.                 {
  149.                     webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0;
  150.                     WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
  151.                     Chrome/51.0.2704.103 Safari/537.36");
  152.                     var response =
  153.                     webClient.DownloadString("http://www.whatismyip.com.tw");
  154.                     string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";
  155.                     ip = Regex.Match(response, pattern).ToString();
  156.                     MessageBox.Show(ip);
  157.                 }
  158.             }
  159.             catch
  160.             {
  161.                 ip = "get error";
  162.             }
  163.             return ip;
  164.         }
  165.         BsonDocument data = new BsonDocument
  166.         {
  167.             { "IP", _IP_str },
  168.             { "Time", DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss") },
  169.         };
  170.         private void button2_Click(object sender, EventArgs e)
  171.         {
  172.             var database = _client.GetDatabase("Test");
  173.             var collection = database.GetCollection<BsonDocument>("Activity");
  174.             collection.DeleteMany(new BsonDocument
  175.                 {
  176.                     { "IP", txt_IP.Text },
  177.                 });
  178.             list_all_data();
  179.         }
  180.         private void button3_Click(object sender, EventArgs e)
  181.         {
  182.             list_all_data();
  183.         }
  184.         private void dataGridView1_CellMouseClick(object sender,
  185.         DataGridViewCellMouseEventArgs e)
  186.         {
  187.             try
  188.             {
  189.                 Int32 selectedCellCount =
  190.                 dataGridView1.GetCellCount(DataGridViewElementStates.Selected);
  191.                 int rowindex = dataGridView1.CurrentRow.Index;
  192.                 if (selectedCellCount > 0)
  193.                 {
  194.                     for (int i = 0; i < selectedCellCount; i++)
  195.                     {
  196.                         txt_id.Text =
  197.                         dataGridView1.Rows[dataGridView1.SelectedCells[i].RowIndex]
  198.                        .Cells[0].Value.ToString();
  199.                     }
  200.                 }
  201.             }
  202.             catch (Exception ex)
  203.             {
  204.             }
  205.         }
  206.         private void btn_update_by_id_Click(object sender, EventArgs e)
  207.         {
  208.             if (txt_id.Text != "")
  209.             {
  210.                 update_data(txt_MB.Text, txt_CPU.Text, txt_GPU.Text, txt_id.Text);
  211.             }
  212.             else
  213.             {
  214.                 MessageBox.Show("請點選要更新的資料");
  215.             }
  216.         }
  217.         private void update_data(String MB, String CPU, String GPU, String id)
  218.         {
  219.             var newDocument = new BsonDocument
  220.             {
  221.                 { "$set", new BsonDocument { { "MB", MB },{ "CPU", CPU }, { "GPU", GPU }
  222.                 } },
  223.             };
  224.             var database = _client.GetDatabase("Test");
  225.             var collection = database.GetCollection<BsonDocument>("Activity");
  226.             var filter = Builders<BsonDocument>.Filter.Eq("_id", ObjectId.Parse(id));
  227.             collection.UpdateOne(filter, newDocument);
  228.             list_all_data();
  229.         }
  230.         private void btn_delete_use_id_Click(object sender, EventArgs e)
  231.         {
  232.             var database = _client.GetDatabase("Test");
  233.             var collection = database.GetCollection<BsonDocument>("Activity");
  234.             if (txt_id.Text != "")
  235.             {
  236.                 collection.DeleteOne(new BsonDocument
  237.                 {
  238.                     { "_id", ObjectId.Parse(txt_id.Text) },
  239.                 });
  240.                 list_all_data();
  241.             }
  242.             else
  243.             {
  244.                 MessageBox.Show("");
  245.             }
  246.         }
  247.         private void btn_find_use_MB_Click(object sender, EventArgs e)
  248.         {
  249.             find_use_MB();
  250.         }
  251.         private async void find_use_MB()
  252.         {
  253.             _tb = new System.Data.DataTable("table");
  254.             _tb.Clear(); //清空表格
  255.             _tb.Rows.Clear();//清空資料
  256.             _tb.Columns.Clear();
  257.             _tb.AcceptChanges();
  258.             dataGridView1.DataSource = null; //清除數據來源
  259.             dataGridView1.DefaultCellStyle.Font = new Font("Verdana", 11,
  260.             FontStyle.Bold);
  261.             dataGridView1.AllowUserToAddRows = false;
  262.             dataGridView1.AutoSizeColumnsMode =
  263.             DataGridViewAutoSizeColumnsMode.AllCells;
  264.             dataGridView1.DataSource = _tb;
  265.             var database = _client.GetDatabase("Test");
  266.             var filter = Builders<BsonDocument>.Filter.Eq("MB", txt_MB.Text);
  267.             var collection = database.GetCollection<BsonDocument>("Activity");
  268.             var LS = await collection.Find(filter).ToListAsync();
  269.             if (LS.Count > 0)
  270.             {
  271.                 List<String> fild_name = new List<string>();
  272.                 fild_name.Clear();
  273.                 fild_name = LS[0].Names.ToList();
  274.                 for (int i = 0; i < fild_name.Count; i++)
  275.                 {
  276.                     DataColumn colItem = new DataColumn(fild_name[i],
  277.                     Type.GetType("System.String"));
  278.                     _tb.Columns.Add(colItem);
  279.                 }
  280.                 for (int i = 0; i < LS.Count; i++)
  281.                 {
  282.                     _NewRow = _tb.NewRow();
  283.                     for (int j = 0; j < fild_name.Count; j++)
  284.                     {
  285.                         _NewRow[fild_name[j]] = LS[i].GetValue(fild_name[j]);
  286.                     }
  287.                     _tb.Rows.Add(_NewRow);
  288.                 }
  289.             }
  290.             else
  291.             {
  292.                 MessageBox.Show("沒有找到相關資料");
  293.             }
  294.         }
  295.     }
  296. }


//========== 實際操作畫面 ==================

以下程式範例主要展示對資料庫進行
新增 修改 刪除 等基本操作
並實際打開資料與與軟體指令結果做比對確認操作正確性

功能一: 搜尋資料庫 Test 內 Activity 內所有資料



功能二: 加入新資料
MB: Z790 CPU: i5-13600k GPU: 4070ti



功能三: 更新剛剛加入的資料把CPU型號改成 i9-14900k  GPU改成 RTX4090



功能四: 找出 MB為 ASUS GA402XV 的所有資料


功能五: 刪除 IP為 192.168.1.1的所有資料


8

0

LINE 分享

相關創作

碧藍航線 自動戰鬥腳本 v2.1.9 蒼閃忍法帖

碧藍航線 自動戰鬥腳本 v2.2.6杰諾瓦的焰火

碧藍航線 自動戰鬥腳本 v2.2.2 奏響鳶尾之歌

留言

開啟 APP

face基於日前微軟官方表示 Internet Explorer 不再支援新的網路標準,可能無法使用新的應用程式來呈現網站內容,在瀏覽器支援度及網站安全性的雙重考量下,為了讓巴友們有更好的使用體驗,巴哈姆特即將於 2019年9月2日 停止支援 Internet Explorer 瀏覽器的頁面呈現和功能。
屆時建議您使用下述瀏覽器來瀏覽巴哈姆特:
。Google Chrome(推薦)
。Mozilla Firefox
。Microsoft Edge(Windows10以上的作業系統版本才可使用)

face我們了解您不想看到廣告的心情⋯ 若您願意支持巴哈姆特永續經營,請將 gamer.com.tw 加入廣告阻擋工具的白名單中,謝謝 !【教學】