teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

コードを修正致しました。

2020/08/27 04:40

投稿

fight51722
fight51722

スコア9

title CHANGED
File without changes
body CHANGED
@@ -11,6 +11,8 @@
11
11
  そのやり方が分からず困っています。
12
12
 
13
13
  下記に途中段階のコードを記載します。
14
+ このコードを実行すると、「ユーザーはログインできませんでした。」
15
+ というエラーメッセージが出ます。
14
16
 
15
17
  ```ここに言語を入力
16
18
  using System;
@@ -35,48 +37,55 @@
35
37
  {
36
38
  InitializeComponent();
37
39
  }
38
-
40
+ //----------------------------------------------------------------------------------------------------------
39
41
  private void button1_Click(object sender, EventArgs e)
40
42
  {
41
- using (var reader = new StreamReader(@"C:\Users\yuhor\OneDrive\デスクトップ\拠点.csv"))
42
- {
43
- string file = reader.ReadToEnd();
44
- }
45
-
46
-
47
43
  SqlConnection conn = new SqlConnection();
48
44
  conn.ConnectionString =
49
45
  @"Data Source=DESKTOP-U6R2QM8\SQLEXPRESS;Initial Catalog=マスタ機能;";
46
+ try
47
+ {
50
48
 
51
- conn.Open();
49
+ conn.Open();
52
50
 
53
- SqlCommand command = conn.CreateCommand();
51
+ SqlCommand command = conn.CreateCommand();
54
- SqlTransaction transaction =conn.BeginTransaction();
52
+ SqlTransaction transaction = conn.BeginTransaction();
55
-
56
- command.Connection = conn;
57
- command.Transaction = transaction;
58
53
 
59
- try
60
- {
61
- command.CommandText =
62
- "Insert into 拠点 (コード, 拠点)";
63
- command.ExecuteNonQuery();
54
+ command.Connection = conn;
55
+ command.Transaction = transaction;
64
56
 
65
- transaction.Commit();
57
+ try
58
+ {
66
59
 
60
+ StreamReader sr = new StreamReader(@"C:\Users\yuhor\OneDrive\デスクトップ\拠点.csv");
61
+ sr.ReadLine();
62
+ while (sr.Peek() > -1)
63
+ {
64
+ string line = sr.ReadLine();
65
+ command.CommandType = CommandType.StoredProcedure;
66
+ command.CommandText = "Insert into 拠点 (コード, 拠点)";
67
+ command.ExecuteNonQuery();
68
+ }
69
+ transaction.Commit();
70
+ sr.Close();
71
+
72
+ }
73
+ catch
74
+ {
75
+ transaction.Rollback();
76
+ }
67
77
  }
68
- catch(Exception)
78
+ catch(Exception ex)
69
- {
79
+ {
70
- transaction.Rollback();
80
+ MessageBox.Show(ex.Message, "データベース接続エラー", MessageBoxButtons.OK, MessageBoxIcon.Error);
71
-
72
81
  }
73
82
  finally
74
83
  {
75
84
  conn.Close();
76
85
  }
77
86
 
78
- }
87
+ }
79
-
88
+
80
89
  }
81
90
  }
82
91
  ```