src/java-tests/isac/users/TestDatabaseConnection.java
author wneuper
Thu, 17 Jan 2008 16:27:03 +0100
changeset 3881 72f0be16d83b
permissions -rw-r--r--
start-work-070517 merged into HEAD
     1 /*
     2  * @author Christian Ropposch, member of the ISAC-team, 
     3  * Copyright (c) 2007 by Christian Ropposch 
     4  * created Jun 13, 2007 5:53:44 PM
     5  * Institute for Softwaretechnology, Graz University of Technology, Austria.
     6  * 
     7  * Use is subject to PGPL license terms.
     8  * 
     9  * Test-case tests if connection to database is 
    10  */
    11 
    12 package isac.users;
    13 
    14 import isac.util.ObjectManagerPaths;
    15 
    16 import java.sql.Connection;
    17 import java.sql.DriverManager;
    18 import java.sql.PreparedStatement;
    19 import java.sql.ResultSet;
    20 import java.sql.SQLException;
    21 
    22 import junit.framework.TestCase;
    23 
    24 public class TestDatabaseConnection extends TestCase {
    25     private boolean logging_enabled_ = false;
    26 
    27     public void testDatabaseConnection() {
    28 	Connection connection = null;
    29 	PreparedStatement statement = null;
    30 	ResultSet rs = null;
    31 
    32 	try {
    33 	    Class.forName("com.mysql.jdbc.Driver");
    34 	} catch (ClassNotFoundException e) {
    35 	    e.printStackTrace();
    36 	}
    37 	try {
    38 	    // connect to database isac
    39 	    logging_enabled_ = ObjectManagerPaths.LOGGER_DATABASE_ENABLED;
    40 	    if (logging_enabled_) {
    41 		connection = DriverManager.getConnection("jdbc:mysql://"
    42 			+ ObjectManagerPaths.LOGGER_DATABASE_PATH + ":"
    43 			+ ObjectManagerPaths.LOGGER_DATABASE_PORT + "/"
    44 			+ ObjectManagerPaths.LOGGER_DATABASE_NAME
    45 			+ "?useUnicode=true&characterEncoding=UTF-8",
    46 			ObjectManagerPaths.LOGGER_DATABASE_USER,
    47 			ObjectManagerPaths.LOGGER_DATABASE_PASSWORD);
    48 		int i = 1;
    49 		// insert some values into table test
    50 		statement = connection.prepareStatement(
    51 			"insert into UserTest(TestValue) values (?)",
    52 			PreparedStatement.RETURN_GENERATED_KEYS);
    53 		while (i <= 10) {
    54 		    statement.setString(1, i + "");
    55 		    statement.execute();
    56 		    // get the last generated key
    57 		    ResultSet keys = statement.getGeneratedKeys();
    58 		    if (keys.next())
    59 			System.out.println("new key: " + keys.getInt(1));
    60 		    i++;
    61 		}
    62 
    63 		// select datarow with value 3
    64 		statement = connection
    65 			.prepareStatement("select * from UserTest where testvalue = ?");
    66 		statement.setString(1, "1");
    67 		rs = statement.executeQuery();
    68 		while (rs.next()) {
    69 		    int test_id = rs.getInt("usertest_id");
    70 		    System.out.println("id of value=1: " + test_id);
    71 		}
    72 	    }
    73 	} catch (SQLException e) {
    74 	    e.printStackTrace();
    75 	}
    76     }
    77 }