使用jdbc创建一个连接到任何数据库的类 [英] Create a class to connect to any database using jdbc

查看:86
本文介绍了使用jdbc创建一个连接到任何数据库的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设计一个Java swing应用程序。我想尝试并使用MVC类型的体系结构,我的UI与实际逻辑分离,以访问数据并连接到数据库。我已经决定创建一个自定义类,其中包含连接到数据库的所有逻辑,然后在我的action事件中为任何特定的表单和按钮调用此类中的方法。这样我可以切换数据库和我需要做的所有事情(如果我有一个包含许多表单的大型代码库)就是更改JDBC连接字符串以连接到oracle而不是MySQL。到目前为止,我有连接到数据库的代码,但我正在试图弄清楚如何将其作为一个类。

I am trying to design a Java swing application. I want to experiment and use an MVC type of architecture whereby my UI is separated from the actual logic to access data and connect to a database. I have decided that I need to create a custom class that contains all the logic to connect to the database and then simply call methods from this class in my action event for any particular form and button. This way I can switch databases and all I need to do (if I have a large code base with many many forms) is change the JDBC connection string to connect to oracle instead of MySQL. So far I have the code to connect to a database but I am trying to figure out how I can make this a class.

try
     {
         Class.forName("com.mysql.jdbc.Driver");
         Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/prototypeeop","root","triala");
         Statement stmt=con.createStatement();
         ResultSet rs=stmt.executeQuery(sql);

然后我将从我的连接类的成员函数返回结果集来处理并显示在屏幕。

I will then return the result set from a member function of my connection class to process and display on the screen.

推荐答案

只需创建一个单独的类并委托他获取与数据库的连接:

Just create a separate class and delegate to him a getting of connection to database:

public class ConnectionManager {
    private static String url = "jdbc:mysql://localhost:3306/prototypeeop";    
    private static String driverName = "com.mysql.jdbc.Driver";   
    private static String username = "root";   
    private static String password = "triala";
    private static Connection con;
    private static String urlstring;

    public static Connection getConnection() {
        try {
            Class.forName(driverName);
            try {
                con = DriverManager.getConnection(urlstring, username, password);
            } catch (SQLException ex) {
                // log an exception. fro example:
                System.out.println("Failed to create the database connection."); 
            }
        } catch (ClassNotFoundException ex) {
            // log an exception. for example:
            System.out.println("Driver not found."); 
        }
        return con;
    }
}

然后在代码中获取如下连接:

Then get the connection in a code as follows:

private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;

con = ConnectionManager.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);

这篇关于使用jdbc创建一个连接到任何数据库的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆