iT邦幫忙

0

讀取資料庫的其中一筆資料

https://ithelp.ithome.com.tw/upload/images/20180417/20109425xe1C63FIoH.jpg

請問如上圖,要抓取其中一筆資料
如在Text Box 填入 20180417 然後按一個Button
會載入 鍵盤 500 20180417 這樣 秀出來
怎麼寫?比較好?
我C#前端都拉好了
剩C#後端還不會寫他用法
string sql = string.Format("select * from sales where Date='{0}'", TexBox1.Text);
現在差 按按鈕秀出GridView 的資料
但還是有點不太會
我是寫程式新手
求解幫忙

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
暐翰
iT邦大師 1 級 ‧ 2018-04-18 09:39:35
最佳解答

Nuget使用套件:Mysql.Data、Dapper

環境:


需要建立一個listbox (圖1)
跟textbox(圖2)

接著Form1.cs新增以下code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dapper;
using MySql.Data.MySqlClient;

namespace 讀取資料庫的其中一筆資料
{
    public partial class Form1 : Form
    {
        MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();

        public Form1()
        {
            InitializeComponent();

            //MYSQL Connection String Init
            conn_string.Server = "Server IP";
            conn_string.UserID = "帳號";
            conn_string.Password = "密碼";
            conn_string.Database = "資料庫名";
            conn_string.Port = 3306;

            //獲取所有商品列表名稱
            using (var conn = new MySqlConnection(conn_string.ToString()))
            {
                conn.Open();
                var test_prices = conn.Query<string>("select item  from TEST_PRICE ").ToList();
                ListViewItem lvi1 = new ListViewItem();
                foreach (var item in test_prices)
                    listBox1.Items.Add(item);
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var item_name = this.listBox1.SelectedItem;
            using (var conn = new MySqlConnection(conn_string.ToString()))
            {
                conn.Open();
                var item = conn.Query("select *  from TEST_PRICE where item = @item_name ", new { item_name })
                    .SingleOrDefault();
                this.textBox1.Text = $"商品 : {item.ITEM} , 價錢 : {item.PRICE} , 銷售日期:{item.DATE}" ;
            }
        }
    }
}

效果圖:


0419更新webform版本:

跟windows form寫法也差不多,以下是修改方式。

PS.需要新增兩個ListView

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Dapper;
using MySql.Data.MySqlClient;

namespace 讀取資料庫的其中一筆資料_webform
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder() {
            Server = "",
            UserID = "",
            Password = "",
            Database = "",
            Port = 3306
        };

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            //獲取所有商品列表名稱
            using (var conn = new MySqlConnection(conn_string.ToString()))
            {
                conn.Open();
                var test_prices = conn.Query<DateTime>("select date  from TEST_PRICE ").ToList();
                foreach (var item in test_prices)
                    this.ListBox1.Items.Add(item.ToString("yyyy/MM/dd"));
            }
        }

        protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var date = this.ListBox1.SelectedItem.Text;
            using (var conn = new MySqlConnection(conn_string.ToString()))
            {
                conn.Open();
                var items = conn.Query("select *  from TEST_PRICE where date = @date ", new { date }).ToList();
                IEnumerable<string> itemsToStrEnum = items.Select(item => $"商品 : {item.ITEM} , 價錢 : {item.PRICE} , 銷售日期:{item.DATE}");
                ListBox2.Items.Clear();
                foreach (var item in itemsToStrEnum)
                    this.ListBox2.Items.Add(item);
            }
        }
    }
}

效果圖:


你先看一下,有不懂的地方跟我講一下 : )

看更多先前的回應...收起先前的回應...
ted8224 iT邦新手 5 級 ‧ 2018-04-18 09:43:34 檢舉

可是 大大 我是 要連接到 一個 Web 這樣,要用到前端後端這樣,謝謝大大回復

暐翰 iT邦大師 1 級 ‧ 2018-04-18 12:31:25 檢舉

你需要.net webform 還是 .net MVC 還是 .net api 技術的寫法?

ted8224 iT邦新手 5 級 ‧ 2018-04-18 13:08:55 檢舉

Webform的
我目前 選擇 可以了
就差按按鈕連接使用所指定資料庫
string sql = string.Format("select * from sales where Date='{0}'", TexBox1.Text);

暐翰 iT邦大師 1 級 ‧ 2018-04-19 08:51:31 檢舉

我更新web form版本了
你在看一下 有問題跟我講

ted8224 iT邦新手 5 級 ‧ 2018-04-19 11:04:07 檢舉

感謝大大

0
丹尼爾
iT邦研究生 2 級 ‧ 2018-04-17 16:17:10
string _retvalue = string.Empty;
using (SqlCommand _sql = new SqlCommand("select item, price from 2018.4.3-test-price where [date] = '20180417'"))
{
  using (SqlDataReader _reader = cmdSQL.ExecuteReader())
  {
      if ( _reader.HasRows)
      {
          _reader.Read();
          _retvalue = string.Format("{0} {1}", _reader["item"], _reader["price"]);
      }
  }
}	
return _retvalue;
0
小魚
iT邦大師 1 級 ‧ 2018-04-18 12:01:30

1.你是用MySql嗎?還是MS-SQL?

2.我不知道為什麼要用while, SQL語法就可以解決

3.SQL語法

SELECT Price + '' + Date FROM sales WHERE Date = @date

然後將@date參數帶入TextBox的值,
我忘記字串能不能這樣接了,
你試試有問題再問.

看更多先前的回應...收起先前的回應...
ted8224 iT邦新手 5 級 ‧ 2018-04-18 13:07:10 檢舉

MySQL

ted8224 iT邦新手 5 級 ‧ 2018-04-18 13:13:32 檢舉

string sql = string.Format("select * from sales where Date='{0}'", TexBox1.Text);
現在差 按按鈕秀出GridView 的資料

小魚 iT邦大師 1 級 ‧ 2018-04-19 12:05:05 檢舉

原來是要用GridView @@
類似這樣吧

MySqlConnection conn = new MySqlConnection(連線字串);
string sql = string.Format("select * from sales where Date='{0}'", TexBox1.Text);
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, conn);
adapter.Fill(dt);
GridView.DataSource = dt;
GridView.DataBind();

但是你的寫法會遭受Sql Injection攻擊...

ted8224 iT邦新手 5 級 ‧ 2018-04-19 13:17:38 檢舉

謝謝大大

0
優悠
iT邦新手 3 級 ‧ 2018-04-19 12:09:07
SqlConnection Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["smallworkCC"].ConnectionString);//你的連線帳密通道

        protected void Page_Load(object sender, EventArgs e)
        {
        //假設你的輸入欄位ID為TextBox1
        //假設你的按鈕ID為Button1
                OWNdataBind();
        }
        
        //你的按鈕事件
        protected void Button1_Click(object sender, EventArgs e)
        {
            OWNdataBind();
        }

        protected void OWNdataBind()
        {
        string FIT=TexBox1.Text;
        string sql="";
        
        if(string.IsNullOrEmpty(FIT))
            sql = "select * from sales ";
        else
            sql = string.Format("select * from sales where Date='{0}'", TexBox1.Text);
            
SqlDataAdapter myAdapter = new SqlDataAdapter(sql, Conn);
            DataSet myDs = new DataSet();
            try
            {
                myAdapter.Fill(myDs, "test");
                DataView view = myDs.Tables["test"].DefaultView;
                GridView1.DataSource = view;
                GridView1.DataBind();
            }
            catch (Exception ex)
            {
                Response.Write("<HR/> 錯誤---- " + ex.ToString());
            }
        }

你先看看
不懂我在修改
新手等級程式碼

補充:可以的話
直接貼妳後端,我比較能理解你卡在哪裡
帳密通道記得打的馬賽克

看更多先前的回應...收起先前的回應...
ted8224 iT邦新手 5 級 ‧ 2018-04-19 13:15:51 檢舉

謝謝大大 回復

優悠 iT邦新手 3 級 ‧ 2018-04-19 18:00:58 檢舉

我小咖 正在從WEBFROM 轉MVC
WEBFROM觀念還在 能多少幫點

優悠 iT邦新手 3 級 ‧ 2018-04-19 18:07:00 檢舉
GridView1_DataBound

GridView1_RowDeleting

GridView1_RowUpdating

GridView1_PageIndexChanged

GridView1_PageIndexChanging

GridView1_RowEditing

GridView1_RowCancelingEdit

GridView1_RowDataBound

需要這些功能再說,當然有上進心點,最好去自己做
GridView玩到最後有些方法無法實現(或者複雜)
jqGrid(JS)這個能比GridView玩到更好

ted8224 iT邦新手 5 級 ‧ 2018-04-20 08:06:56 檢舉

好的 謝謝您...大大 感謝您回復

我要發表回答

立即登入回答