こんにちは。
当方、プログラム初心者です。
C#でSQL ServerにあるデータベースをDataSetに格納したいと思い、以下のコードを書きました。
作っている環境はVisual Studio 2017、Windowsフォームアプリケーションを使用しています。
サンプルとして作ったSQL ServerのデータベースはWindows認証でログイン、
テーブル名はdbo.testItem、
商品コード,商品名,価格,単位の4つの列を作りました。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void dbSearch_Click(object sender, EventArgs e) { SqlConnection connection = new SqlConnection("data source ='SQL Serverのサーバ名';initial catalog = 'SQL Serverのデータベース名前'; Integrated Security = True;Connection Timeout = 10;MultipleActiveResultSets = True"); connection.Open(); SqlCommand command = new SqlCommand(); command.Connection = connection; command.CommandText = "SELECT 商品コード,商品名,価格,単位 FROM testItem"; DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = command; adapter.Fill(ds); command.Dispose(); connection.Close(); connection.Dispose(); } } }
上記のコードで正しいかと思ったのですが、VisualStudioでデバックボタンを開始した後に、DataSetにカーソルを当ててクイックビューを見ても、空と表示されます。
DataSetを作っただけでは空だから、元のデータベースに合わせてDataSetにも4つの列を含んだテーブルなどを作成する必要があるということでしょうか?
それとも、テーブルは自動で作ってくれて他に間違っているところがあるのでしょうか?
何かおかしい点などがあれば、是非教えて頂きたいです。
よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー