bump product version to 4.2.0.1
[LibreOffice.git] / qadevOOo / runner / util / DBTools.java
blob42a96c03232463d06c91e641bc95cc736295b823
1 /*
2 * This file is part of the LibreOffice project.
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 * This file incorporates work covered by the following license notice:
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
19 package util;
21 import com.sun.star.uno.Exception;
22 import java.io.PrintWriter ;
24 // access the implementations via names
25 import com.sun.star.uno.XInterface;
26 import com.sun.star.lang.XMultiServiceFactory;
27 import com.sun.star.uno.UnoRuntime;
29 import com.sun.star.beans.PropertyValue;
30 import com.sun.star.beans.XPropertySet;
31 import com.sun.star.sdbc.XConnection ;
32 import com.sun.star.sdbc.XResultSet ;
33 import com.sun.star.sdbc.XResultSetUpdate ;
34 import com.sun.star.sdbc.XStatement ;
35 import com.sun.star.sdbc.XRowUpdate ;
36 import com.sun.star.util.Date ;
37 import com.sun.star.uno.XNamingService ;
38 import com.sun.star.task.XInteractionHandler ;
39 import com.sun.star.sdb.XCompletedConnection ;
40 import com.sun.star.container.XEnumeration ;
41 import com.sun.star.container.XEnumerationAccess ;
42 import com.sun.star.io.XInputStream ;
43 import com.sun.star.io.XTextInputStream ;
44 import com.sun.star.io.XDataInputStream ;
45 import com.sun.star.container.XNameAccess ;
46 import com.sun.star.frame.XStorable;
47 import com.sun.star.sdb.XDocumentDataSource;
48 import com.sun.star.sdbc.XCloseable ;
49 import java.sql.Statement;
50 import java.sql.Connection;
51 import java.sql.DriverManager;
53 /**
54 * Provides useful methods for working with SOffice databases.
55 * Database creation, data transfering, outputting infromation.
57 public class DBTools {
59 private XMultiServiceFactory xMSF = null ;
60 private XNamingService dbContext = null ;
61 //JDBC driver
62 public final static String TST_JDBC_DRIVER = "org.gjt.mm.mysql.Driver";
64 // constants for TestDB table column indexes
65 public final static int TST_STRING = 1 ;
66 public final static int TST_INT = 2 ;
67 public final static int TST_DOUBLE = 5 ;
68 public final static int TST_DATE = 6 ;
69 public final static int TST_BOOLEAN = 10 ;
70 public final static int TST_CHARACTER_STREAM = 11 ;
71 public final static int TST_BINARY_STREAM = 12 ;
73 // constants for TestDB columns names
74 public final static String TST_STRING_F = "_TEXT" ;
75 public final static String TST_INT_F = "_INT" ;
76 public final static String TST_DOUBLE_F = "_DOUBLE" ;
77 public final static String TST_DATE_F = "_DATE" ;
78 public final static String TST_BOOLEAN_F = "_BOOL" ;
79 public final static String TST_CHARACTER_STREAM_F = "_MEMO1" ;
80 public final static String TST_BINARY_STREAM_F = "_MEMO2" ;
82 /**
83 * Values for filling test table.
85 public final static Object[][] TST_TABLE_VALUES = new Object[][] {
86 {"String1", new Integer(1), null, null, new Double(1.1),
87 new Date((short) 1,(short) 1, (short) 2001), null, null, null,
88 Boolean.TRUE, null, null},
89 {"String2", new Integer(2), null, null, new Double(1.2),
90 new Date((short) 2, (short) 1,(short) 2001), null, null, null,
91 Boolean.FALSE, null, null},
92 {null, null, null, null, null,
93 null, null, null, null,
94 null, null, null}
95 } ;
97 /**
98 * Array of lengths of streams for each row in of the
99 * <code>TST_TABLE_VALUES</code> constants.
101 public final static int[] TST_STREAM_LENGTHS = {0, 0, 0} ;
104 * It's just a structure with some useful methods for representing
105 * <code>com.sun.star.sdb.DataSource</code> service. All this
106 * service's properties are stored in appropriate class fields.
107 * Class also allows to construct its instances using service
108 * information, and create new service instance upon class
109 * fields.
110 * @see com.sun.star.sdb.DataSource
112 public class DataSourceInfo {
114 * Representation of <code>'Name'</code> property.
116 public String Name = null ;
118 * Representation of <code>'URL'</code> property.
120 public String URL = null ;
122 * Representation of <code>'Info'</code> property.
124 public PropertyValue[] Info = null ;
126 * Representation of <code>'User'</code> property.
128 public String User = null ;
130 * Representation of <code>'Password'</code> property.
132 public String Password = null ;
134 * Representation of <code>'IsPasswordRequired'</code> property.
136 public Boolean IsPasswordRequired = null ;
138 * Representation of <code>'SuppressVersionColumns'</code> property.
140 public Boolean SuppressVersionColumns = null ;
142 * Representation of <code>'IsReadOnly'</code> property.
144 public Boolean IsReadOnly = null ;
146 * Representation of <code>'TableFilter'</code> property.
148 public String[] TableFilter = null ;
150 * Representation of <code>'TableTypeFilter'</code> property.
152 public String[] TableTypeFilter = null ;
155 * Creates an empty instance.
157 public DataSourceInfo()
162 * Creates an instance laying upon specified DataSource.
163 * @param dataSource All source properties are copied into
164 * class fields.
166 public DataSourceInfo(Object dataSource) {
167 XPropertySet xProps = UnoRuntime.queryInterface(XPropertySet.class, dataSource) ;
169 try {
170 Name = (String)xProps.getPropertyValue("Name") ;
171 URL = (String)xProps.getPropertyValue("URL") ;
172 Info = (PropertyValue[])xProps.getPropertyValue("Info") ;
173 User = (String)xProps.getPropertyValue("User") ;
174 Password = (String)xProps.getPropertyValue("Password") ;
175 IsPasswordRequired = (Boolean)xProps.getPropertyValue("IsPasswordRequired") ;
176 SuppressVersionColumns = (Boolean)
177 xProps.getPropertyValue("SuppressVersionColumns") ;
178 IsReadOnly = (Boolean)xProps.getPropertyValue("IsReadOnly") ;
179 TableFilter = (String[])xProps.getPropertyValue("TableFilter") ;
180 TableTypeFilter = (String[])xProps.getPropertyValue("TableTypeFilter") ;
181 } catch (com.sun.star.beans.UnknownPropertyException e) {
182 System.err.println("util.DBTools.DataSourceInfo: Error retrieving property") ;
183 e.printStackTrace(System.err) ;
184 } catch (com.sun.star.lang.WrappedTargetException e) {
185 System.err.println("util.DBTools.DataSourceInfo: Error retrieving property") ;
186 e.printStackTrace(System.err) ;
191 * Prints datasource info.
192 * @param out Stream to which information is printed.
194 public void printInfo(PrintWriter out) {
195 out.println("Name = '" + Name + "'") ;
196 out.println(" URL = '" + URL + "'") ;
197 out.print(" Info = ") ;
198 if (Info == null) out.println("null") ;
199 else {
200 out.print("{") ;
201 for (int i = 0; i < Info.length; i++) {
202 out.print(Info[i].Name + " = '" + Info[i].Value + "'") ;
203 if (i + 1 < Info.length) out.print("; ") ;
205 out.println("}") ;
207 out.println(" User = '" + User + "'") ;
208 out.println(" Password = '" + Password + "'") ;
209 out.println(" IsPasswordRequired = '" + IsPasswordRequired + "'") ;
210 out.println(" SuppressVersionColumns = '" + SuppressVersionColumns + "'") ;
211 out.println(" IsReadOnly = '" + IsReadOnly + "'") ;
212 out.print(" TableFilter = ") ;
213 if (TableFilter == null) out.println("null") ;
214 else {
215 out.print("{") ;
216 for (int i = 0; i < TableFilter.length; i++) {
217 out.print("'" + TableFilter[i] + "'") ;
218 if (i+1 < TableFilter.length) out.print("; ");
220 out.println("}") ;
222 out.print(" TableTypeFilter = ") ;
223 if (TableTypeFilter == null) out.println("null") ;
224 else {
225 out.print("{") ;
226 for (int i = 0; i < TableTypeFilter.length; i++) {
227 out.print("'" + TableTypeFilter[i] + "'") ;
228 if (i+1 < TableTypeFilter.length) out.print("; ");
230 out.println("}") ;
235 * Creates new <code>com.sun.star.sdb.DataSource</code> service
236 * instance and copies all fields (which are not null) to
237 * appropriate service properties.
238 * @return <code>com.sun.star.sdb.DataSource</code> service.
240 public Object getDataSourceService() throws Exception
242 Object src = xMSF.createInstance("com.sun.star.sdb.DataSource") ;
244 XPropertySet props = UnoRuntime.queryInterface
245 (XPropertySet.class, src) ;
247 if (Name != null) props.setPropertyValue("Name", Name) ;
248 if (URL != null) props.setPropertyValue("URL", URL) ;
249 if (Info != null) props.setPropertyValue("Info", Info) ;
250 if (User != null) props.setPropertyValue("User", User) ;
251 if (Password != null) props.setPropertyValue("Password", Password) ;
252 if (IsPasswordRequired != null) props.setPropertyValue("IsPasswordRequired", IsPasswordRequired) ;
253 if (SuppressVersionColumns != null) props.setPropertyValue("SuppressVersionColumns", SuppressVersionColumns) ;
254 if (IsReadOnly != null) props.setPropertyValue("IsReadOnly", IsReadOnly) ;
255 if (TableFilter != null) props.setPropertyValue("TableFilter", TableFilter) ;
256 if (TableTypeFilter != null) props.setPropertyValue("TableTypeFilter", TableTypeFilter) ;
258 return src ;
263 * Creates class instance.
264 * @param xMSF <code>XMultiServiceFactory</code>.
266 public DBTools(XMultiServiceFactory xMSF, PrintWriter _logger )
268 this.xMSF = xMSF ;
269 try {
270 Object cont = xMSF.createInstance("com.sun.star.sdb.DatabaseContext") ;
272 dbContext = UnoRuntime.queryInterface
273 (XNamingService.class, cont) ;
275 } catch (com.sun.star.uno.Exception e) {}
279 * Returns new instance of <code>DataSourceInfo</code> class.
281 public DataSourceInfo newDataSourceInfo() { return new DataSourceInfo() ;}
284 * Returns new instance of <code>DataSourceInfo</code> class.
286 public DataSourceInfo newDataSourceInfo(Object dataSource) {
287 return new DataSourceInfo(dataSource);
291 * Registers the datasource on the specified name in
292 * <code>DatabaseContext</code> service.
293 * @param name Name which dataSource will have in global context.
294 * @param dataSource <code>DataSource</code> object which is to
295 * be registered.
297 public void registerDB(String name, Object dataSource)
298 throws com.sun.star.uno.Exception {
300 dbContext.registerObject(name, dataSource) ;
305 * First tries to revoke the datasource with the specified
306 * name and then registers a new one.
307 * @param name Name which dataSource will have in global context.
308 * @param dataSource <code>DataSource</code> object which is to
309 * be registered.
311 public void reRegisterDB(String name, Object dataSource)
312 throws com.sun.star.uno.Exception {
314 try {
315 revokeDB(name) ;
316 } catch (com.sun.star.uno.Exception e) {}
318 XDocumentDataSource xDDS = UnoRuntime.queryInterface(XDocumentDataSource.class, dataSource);
319 XStorable store = UnoRuntime.queryInterface(XStorable.class,
320 xDDS.getDatabaseDocument());
321 String aFile = utils.getOfficeTemp(xMSF) + name + ".odb";
322 store.storeAsURL(aFile, new PropertyValue[] { });
324 registerDB(name, dataSource) ;
328 * RESERVED. Not used.
330 public XConnection connectToTextDB(String contextName,
331 String dbDir, String fileExtension)
332 throws com.sun.star.uno.Exception {
334 try {
335 XInterface newSource = (XInterface) xMSF.createInstance
336 ("com.sun.star.sdb.DataSource") ;
338 XPropertySet xSrcProp = UnoRuntime.queryInterface(XPropertySet.class, newSource);
340 xSrcProp.setPropertyValue("URL", "sdbc:text:" + dirToUrl(dbDir));
342 PropertyValue extParam = new PropertyValue() ;
343 extParam.Name = "EXT" ;
344 extParam.Value = fileExtension ;
346 xSrcProp.setPropertyValue("Info", new PropertyValue[] {extParam}) ;
348 dbContext.registerObject(contextName, newSource) ;
350 Object handler = xMSF.createInstance("com.sun.star.sdb.InteractionHandler");
351 XInteractionHandler xHandler = UnoRuntime.queryInterface(XInteractionHandler.class, handler) ;
353 XCompletedConnection xSrcCon = UnoRuntime.queryInterface(XCompletedConnection.class, newSource) ;
355 XConnection con = xSrcCon.connectWithCompletion(xHandler) ;
357 return con ;
358 } finally {
359 try {
360 dbContext.revokeObject(contextName) ;
361 } catch (Exception e) {}
366 * Registers DBase database (directory with DBF files) in the
367 * global DB context, then connects to it.
368 * @param contextName Name under which DB will be registered.
369 * @param dbDir The directory with DBF tables.
370 * @return Connection to the DB.
372 public XConnection connectToDBase(String contextName,
373 String dbDir)
374 throws com.sun.star.uno.Exception {
376 try {
377 XInterface newSource = (XInterface) xMSF.createInstance
378 ("com.sun.star.sdb.DataSource") ;
380 XPropertySet xSrcProp = UnoRuntime.queryInterface(XPropertySet.class, newSource);
381 xSrcProp.setPropertyValue("URL", "sdbc:dbase:" + dirToUrl(dbDir));
383 dbContext.registerObject(contextName, newSource) ;
385 XConnection con = connectToSource(newSource) ;
387 return con ;
388 } catch(com.sun.star.uno.Exception e) {
389 try {
390 dbContext.revokeObject(contextName) ;
391 } catch (Exception ex) {}
393 throw e ;
398 * Performs connection to DataSource specified.
399 * @param dbSource <code>com.sun.star.sdb.DataSource</code> service
400 * specified data source which must be already registered in the
401 * <code>DatabaseContext</code> service.
402 * @return Connection to the data source.
404 public XConnection connectToSource(Object dbSource)
405 throws com.sun.star.uno.Exception {
407 Object handler = xMSF.createInstance("com.sun.star.sdb.InteractionHandler");
408 XInteractionHandler xHandler = UnoRuntime.queryInterface(XInteractionHandler.class, handler) ;
410 XCompletedConnection xSrcCon = UnoRuntime.queryInterface(XCompletedConnection.class, dbSource) ;
412 return xSrcCon.connectWithCompletion(xHandler) ;
416 * Registers Test data source in the <code>DatabaseContext</code> service.
417 * This source always has name <code>'APITestDatabase'</code> and it
418 * is registered in subdirectory <code>TestDB</code> of directory
419 * <code>docPath</code> which is supposed to be a directory with test
420 * documents, but can be any other (it must have subdirectory with DBF
421 * tables). If such data source doesn't exists or exists with
422 * different URL it is recreated and reregistered.
423 * @param docPath Path to database <code>TestDB</code> directory.
424 * @return <code>com.sun.star.sdb.DataSource</code> service
425 * implementation which represents TestDB.
427 public Object registerTestDB(String docPath)
428 throws com.sun.star.uno.Exception {
430 String testURL = null ;
431 if (docPath.endsWith("/") || docPath.endsWith("\\"))
432 testURL = dirToUrl(docPath + "TestDB") ;
433 else
434 testURL = dirToUrl(docPath + "/" + "TestDB") ;
435 testURL = "sdbc:dbase:" + testURL ;
437 String existURL = null ;
439 XNameAccess na = UnoRuntime.queryInterface
440 (XNameAccess.class, dbContext) ;
442 Object src = null ;
443 if (na.hasByName("APITestDatabase")) {
444 src = dbContext.getRegisteredObject("APITestDatabase") ;
446 XPropertySet srcPs = UnoRuntime.queryInterface
447 (XPropertySet.class, src) ;
449 existURL = (String) srcPs.getPropertyValue("URL") ;
452 if (src == null || !testURL.equals(existURL)) {
453 // test data source must be reregistered.
454 DataSourceInfo info = new DataSourceInfo() ;
455 info.URL = testURL ;
456 src = info.getDataSourceService() ;
457 reRegisterDB("APITestDatabase", src) ;
458 src = dbContext.getRegisteredObject("APITestDatabase") ;
461 return src ;
465 * Connects to <code>DataSource</code> specially created for testing.
466 * This source always has name <code>'APITestDatabase'</code> and it
467 * is registered in subdirectory <code>TestDB</code> of directory
468 * <code>docPath</code> which is supposed to be a directory with test
469 * documents, but can be any other (it must have subdirectory with DBF
470 * tables). If such data source doesn't exists or exists with
471 * different URL it is recreated and reregistered. Finally connection
472 * performed.
473 * @param docPath Path to database <code>TestDB</code> directory.
474 * @return Connection to test database.
476 public XConnection connectToTestDB(String docPath)
477 throws com.sun.star.uno.Exception {
479 return connectToSource(registerTestDB(docPath)) ;
483 * Empties the table in the specified source.
484 * @param con Connection to the DataSource where appropriate
485 * table exists.
486 * @param table The name of the table where all rows will be deleted.
487 * @return Number of rows deleted.
490 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
491 // Currently doesn't work because of bugs 85509, 85510
493 public int deleteAllRows(XConnection con, String table)
494 throws com.sun.star.sdbc.SQLException {
496 XStatement stat = con.createStatement() ;
498 XResultSet set = stat.executeQuery("SELECT * FROM " + table) ;
500 XResultSetUpdate updt = UnoRuntime.queryInterface
501 (XResultSetUpdate.class, set) ;
503 int count = 0 ;
504 set.last() ;
505 int rowNum = set.getRow() ;
506 set.first() ;
508 for (int i = 0; i < rowNum; i++) {
509 updt.deleteRow() ;
510 set.next() ;
511 count ++ ;
514 XCloseable xClose = UnoRuntime.queryInterface
515 (XCloseable.class, set) ;
516 xClose.close() ;
518 return count ;
522 * Inserts row into test table of the specified connection.
523 * Test table has some predefined format which includes as much
524 * field types as possible. For every column type constants
525 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
526 * are declared for column index fast find.
527 * @param con Connection to data source where test table exists.
528 * @param table Test table name.
529 * @param values Values to be inserted into test table. Values of
530 * this array inserted into appropriate fields depending on their
531 * types. So <code>String</code> value of the array is inserted
532 * into the field of <code>CHARACTER</code> type, etc.
533 * @param streamLength Is optional. It is used only if in values
534 * list <code>XCharacterInputStream</code> or <code>XBinaryInputStream
535 * </code> types specified. In this case the parameter specifies
536 * the length of the stream for inserting.
538 public void addRowToTestTable(XConnection con, String table, Object[] values,
539 int streamLength)
540 throws com.sun.star.sdbc.SQLException {
542 XStatement stat = con.createStatement() ;
544 XResultSet set = stat.executeQuery("SELECT * FROM " + table) ;
546 XResultSetUpdate updt = UnoRuntime.queryInterface
547 (XResultSetUpdate.class, set) ;
549 XRowUpdate rowUpdt = UnoRuntime.queryInterface
550 (XRowUpdate.class, set) ;
552 updt.moveToInsertRow() ;
554 for (int i = 0; i < values.length; i++) {
555 if (values[i] instanceof String) {
556 rowUpdt.updateString(TST_STRING, (String) values[i]) ;
557 } else
558 if (values[i] instanceof Integer) {
559 rowUpdt.updateInt(TST_INT, ((Integer) values[i]).intValue()) ;
560 } else
561 if (values[i] instanceof Double) {
562 rowUpdt.updateDouble(TST_DOUBLE, ((Double) values[i]).doubleValue()) ;
563 } else
564 if (values[i] instanceof Date) {
565 rowUpdt.updateDate(TST_DATE, (Date) values[i]) ;
566 } else
567 if (values[i] instanceof Boolean) {
568 rowUpdt.updateBoolean(TST_BOOLEAN, ((Boolean) values[i]).booleanValue()) ;
569 } else
570 if (values[i] instanceof XTextInputStream) {
571 rowUpdt.updateCharacterStream(TST_CHARACTER_STREAM, (XInputStream) values[i],
572 streamLength) ;
573 } else
574 if (values[i] instanceof XDataInputStream) {
575 rowUpdt.updateBinaryStream(TST_BINARY_STREAM, (XInputStream) values[i],
576 streamLength) ;
580 updt.insertRow() ;
582 XCloseable xClose = UnoRuntime.queryInterface
583 (XCloseable.class, set) ;
584 xClose.close() ;
588 * Initializes test table specified of the connection specified.
589 * Deletes all record from table, and then inserts data from
590 * <code>TST_TABLE_VALUES</code> constant array. <p>
591 * Test table has some predefined format which includes as much
592 * field types as possible. For every column type constants
593 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
594 * are declared for column index fast find.
595 * @param con Connection to data source where test table exists.
596 * @param table Test table name.
598 public void initializeTestTable(XConnection con, String table)
599 throws com.sun.star.sdbc.SQLException {
601 deleteAllRows(con, table) ;
603 for (int i = 0; i < TST_TABLE_VALUES.length; i++) {
604 addRowToTestTable(con, table, TST_TABLE_VALUES[i], TST_STREAM_LENGTHS[i]) ;
609 * Prints full info about currently registered DataSource's.
611 public void printRegisteredDatabasesInfo(PrintWriter out) {
612 XEnumerationAccess dbContEA = UnoRuntime.queryInterface(XEnumerationAccess.class, dbContext) ;
614 XEnumeration xEnum = dbContEA.createEnumeration() ;
616 out.println("DatabaseContext registered DataSource's :") ;
617 while (xEnum.hasMoreElements()) {
618 try {
619 DataSourceInfo inf = new DataSourceInfo(xEnum.nextElement()) ;
620 inf.printInfo(out) ;
621 } catch (com.sun.star.container.NoSuchElementException e) {}
622 catch (com.sun.star.lang.WrappedTargetException e) {}
627 * Convert system pathname to SOffice URL string
628 * (for example 'C:\Temp\DBDir\' -> 'file:///C|/Temp/DBDir/').
629 * (for example '\\server\Temp\DBDir\' -> 'file://server/Temp/DBDir/').
630 * Already converted string retured unchanged.
632 public static String dirToUrl(String dir) {
633 String retVal = null;
634 if (dir.startsWith("file:/")) retVal = dir;
635 else {
636 retVal = dir.replace(':', '|').replace('\\', '/');
638 if (dir.startsWith("\\\\")) {
639 retVal = "file:" + retVal;
642 else retVal = "file:///" + retVal ;
644 return retVal;
648 * Revokes datasource from global DB context.
649 * @param name DataSource name to be revoked.
651 public void revokeDB(String name) throws com.sun.star.uno.Exception
653 dbContext.revokeObject(name) ;
657 * Initializes test table specified of the connection specified
658 * using JDBC driver. Drops table with the name <code>tbl_name</code>,
659 * creates new table with this name and then inserts data from
660 * <code>TST_TABLE_VALUES</code> constant array. <p>
661 * Test table has some predefined format which includes as much
662 * field types as possible. For every column type constants
663 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
664 * are declared for column index fast find.
665 * @param tbl_name Test table name.
667 public void initTestTableUsingJDBC(String tbl_name, DataSourceInfo dsi)
668 throws java.sql.SQLException,
669 ClassNotFoundException {
670 //register jdbc driver
671 if ( dsi.Info[0].Name.equals("JavaDriverClass") ) {
672 Class.forName((String)dsi.Info[0].Value);
673 } else {
674 Class.forName(TST_JDBC_DRIVER);
677 //getting connection
678 Connection connection = null;
680 connection = DriverManager.getConnection(
681 dsi.URL, dsi.User, dsi.Password);
682 Statement statement = connection.createStatement();
684 //drop table
685 dropMySQLTable(statement, tbl_name);
687 //create table
688 createMySQLTable(statement, tbl_name);
690 //insert some content
691 insertContentMySQLTable(statement, tbl_name);
695 * Inserts data from <code>TST_TABLE_VALUES</code> constant array
696 * to test table <code>tbl_name</code>.
697 * @param statement object used for executing a static SQL
698 * statement and obtaining the results produced by it.
699 * @param tbl_name Test table name.
701 protected void insertContentMySQLTable(Statement statement, String tbl_name)
702 throws java.sql.SQLException {
705 for(int i = 0; i < DBTools.TST_TABLE_VALUES.length; i++) {
706 String query = "insert into " + tbl_name + " values (";
707 int j = 0;
708 while(j < DBTools.TST_TABLE_VALUES[i].length) {
709 if (j > 0) {
710 query += ", ";
712 Object value = DBTools.TST_TABLE_VALUES[i][j];
713 if (value instanceof String ||
714 value instanceof Date) {
715 query += "'";
717 if (value instanceof Date) {
718 Date date = (Date)value;
719 query += date.Year + "-" + date.Month +
720 "-" + date.Day;
721 } else if (value instanceof Boolean) {
722 query += (((Boolean)value).booleanValue())
723 ? "1" : "0";
724 } else {
725 query += value;
728 if (value instanceof String ||
729 value instanceof Date) {
730 query += "'";
732 j++;
734 query += ")";
735 statement.executeUpdate(query);
740 * Creates test table specified.
741 * Test table has some predefined format which includes as much
742 * field types as possible. For every column type constants
743 * {@link #TST_STRING TST_STRING}, {@link #TST_INT TST_INT}, etc.
744 * are declared for column index fast find.
745 * @param statement object used for executing a static SQL
746 * statement and obtaining the results produced by it.
747 * @param tbl_name Test table name.
749 protected void createMySQLTable(Statement statement, String tbl_name)
750 throws java.sql.SQLException {
752 final String empty_col_name = "Column";
753 int c = 0;
754 String query = "create table " + tbl_name + " (";
755 for (int i = 0; i < TST_TABLE_VALUES[0].length; i++) {
756 if (i > 0) query += ",";
758 switch(i + 1) {
759 case TST_BINARY_STREAM:
760 query += TST_BINARY_STREAM_F + " BLOB";
761 break;
762 case TST_BOOLEAN:
763 query += TST_BOOLEAN_F + " TINYINT";
764 break;
765 case TST_CHARACTER_STREAM:
766 query += TST_CHARACTER_STREAM_F + " TEXT";
767 break;
768 case TST_DATE:
769 query += TST_DATE_F + " DATE";
770 break;
771 case TST_DOUBLE:
772 query += TST_DOUBLE_F + " DOUBLE";
773 break;
774 case TST_INT:
775 query += TST_INT_F + " INT";
776 break;
777 case TST_STRING:
778 query += TST_STRING_F + " TEXT";
779 break;
780 default: query += empty_col_name + (c++) + " INT";
781 if (c == 1) {
782 query += " NOT NULL AUTO_INCREMENT";
786 query += ", PRIMARY KEY (" + empty_col_name + "0)";
787 query += ")";
788 statement.execute(query);
792 * Drops table.
793 * @param statement object used for executing a static SQL
794 * statement and obtaining the results produced by it.
795 * @param tbl_name Test table name.
797 protected void dropMySQLTable(Statement statement, String tbl_name)
798 throws java.sql.SQLException {
799 statement.executeUpdate("drop table if exists " + tbl_name);