KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jasperreports > mysql > Database


1 package net.sf.jasperreports.mysql;
2
3 import java.sql.Connection JavaDoc;
4 import java.sql.DriverManager JavaDoc;
5
6 /**
7  * Contains all the database configuration information
8  * and methods to connect to a database.
9  */

10 public class Database
11 {
12
13     private Connection JavaDoc connection;
14     //feilds to connect to a database
15
String JavaDoc name = null;
16     String JavaDoc login = null;
17     String JavaDoc pass = null;
18     String JavaDoc url = null;
19
20     /**
21      * a wrapper for connect that can see the database params.
22      *
23      * @return - the Connection object.
24      */

25     public Connection JavaDoc getConnection()
26     {
27         //check if already connected
28
if (connection == null)
29         {
30             connection = connect(url, login, pass);
31         }
32         return connection;
33     }
34
35     /**
36      * connects to a database using the params below.
37      *
38      * @param dbURL - the url to connect to.
39      * @param dbLogin - the login name for this databse.
40      * @param dbPass - the pasword for this database.
41      * @return - the connection object.
42      * exits if it can not connect.
43      */

44     private static Connection JavaDoc connect(String JavaDoc dbURL, String JavaDoc dbLogin,
45                                       String JavaDoc dbPass)
46     {
47         Connection JavaDoc con = null;
48         try
49         {
50             //load the driver
51
Class.forName("com.mysql.jdbc.Driver");
52             //try to connect
53
con = DriverManager.getConnection(dbURL, dbLogin, dbPass);
54         }
55                 //DOH! it didn't work...
56
catch (Exception JavaDoc e)
57         {
58             e.printStackTrace();
59             System.out.println("Exception: " + e.getMessage());
60             //the database was not found
61
if (e.getMessage().indexOf("Unknown database") != -1)
62             {
63                 System.err.println(
64                         "\n\nI can't seem to find the database. Please create it");
65             }
66             //username or password was incorrect or some other problem
67
else
68             {
69                 System.out.println(
70                         "\n\nI can't connect to the database.\n"
71                         +
72                         "It is likely that the username or password was incorrect.");
73             }
74             System.exit(1);
75         }
76         System.err.println(
77                 "Connected to database (" + dbURL + ") successfully!");
78         return con;
79     }
80 }
81
Popular Tags