回答編集履歴

1

コメントでの指摘について追記

2016/03/06 09:44

投稿

umed0025
umed0025

スコア851

test CHANGED
@@ -167,3 +167,81 @@
167
167
  eclipse+JUnit関連の参考資料
168
168
 
169
169
  http://qiita.com/takehiro224/items/a5d4265c4a1b36b0919c
170
+
171
+
172
+
173
+
174
+
175
+ 追記:
176
+
177
+ 同じインスタスでないので動くのでは?とコメントで別の方から突っ込みを受けたのですが、
178
+
179
+ PreparedStatementについては元々同じインスタンスではないですよ。
180
+
181
+ 以下のコードでも正常に動きます。
182
+
183
+ コネクションの処理や、例外の処理についてお勧めではないです。
184
+
185
+
186
+
187
+ ```
188
+
189
+ package sandbox;
190
+
191
+
192
+
193
+ import java.sql.Connection;
194
+
195
+ import java.sql.DriverManager;
196
+
197
+ import java.sql.PreparedStatement;
198
+
199
+
200
+
201
+ public class SQLSample2 {
202
+
203
+ private static final String sql1 = "INSERT INTO foo (No,Value)VALUES (?,?)";
204
+
205
+ private static final String sql2 = "INSERT INTO bar (No,Value)VALUES (?,?)";
206
+
207
+
208
+
209
+ public void mySqlMultiTableInsertSample() {
210
+
211
+ try {
212
+
213
+ Class.forName("com.mysql.jdbc.Driver");
214
+
215
+ Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/sandbox?useSSL=true",
216
+
217
+ "root", "admin");
218
+
219
+ PreparedStatement ps1 = connection.prepareStatement(sql1);
220
+
221
+ ps1.setInt(1, 1);
222
+
223
+ ps1.setString(2, "value1");
224
+
225
+ ps1.executeUpdate();
226
+
227
+ ps1 = connection.prepareStatement(sql2);
228
+
229
+ ps1.setInt(1, 2);
230
+
231
+ ps1.setString(2, "value2");
232
+
233
+ ps1.executeUpdate();
234
+
235
+ connection.close();
236
+
237
+ } catch (Exception e) {
238
+
239
+ throw new RuntimeException(e);
240
+
241
+ }
242
+
243
+ }
244
+
245
+ }
246
+
247
+ ```