2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

VisualStudio - C# - DB接続 - コードで

Last updated at Posted at 2019-04-16

ググれば一発と思ったら何度か試すハメになったので

書き方

dbConnect.csharp
string dbConnect = @"DataSource           =  (localdb)\MSSQLLocalDB;
                     Initial Catalog      = TESTDB;
                     Integrated Security  = True;";
/*(localdb)\MSSQLLocalDB : 接続先
  TESTDB                 : 接続先DB
  True                   : 呪文*/

ちなみに下記みたいにクラスに分けると便利

dbConnect.csharp
using System.Data.SqlClient;

public void load()
{
  /* 今回データグリッドビューにデータ入れる時の処理 */
    /* 書いてたときのなのでそれもコメントで追記      */
    /* var dt_code = new DataTable();            */

    // 変数に接続文字列を代入
    var conStr = construct.dbConnect;

    // usingの()内で恐らくDB接続情報取得 確認して
    using (var connect = new SqlConnection(conStr))
    {
        var cmd = connect.CreateCommand();
        cmd.CommandText = "SELECT * FROM TABLE";

        // DBに接続
        var sda = new SqlDataAdapter(cmd);
        /* sda内の接続情報でdt_code(データテーブル)
           にデータ入力
        sda.Fill(dt_code);                         */
    }
    /* データグリッドビューのソースにテーブルのデータを入れる
    DataGridView1.DataSource = dt_code;            */
}


static class construct
{
    string dbConnect = @"DataSource           =  (localdb)\MSSQLLocalDB;
                         Initial Catalog      = TESTDB;
                         Integrated Security  = True;";
    /*(localdb)\MSSQLLocalDB : 接続先
      TESTDB                 : 接続先DB
      True                   : 呪文*/
}
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?