打开和关闭不同类的连接 [英] Opening and closing connection on different class
本文介绍了打开和关闭不同类的连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将代码分成3部分。我是指3个不同的文件。第一部分用于连接SQL服务器,第二部分用于操作数据库,第三部分用于关闭连接。代码只是一个例子。
Is it possible to separate the code into 3 part. I mean 3 different file. First part for connecting to SQL server, second part for manipulating database and third part is for closing the connection. The code is just an example.
/**
* CloseConnection.java
* Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
*/
import java.sql.*;
public class CloseConnection {
public static void main(String [] args) {
Connection con = null;
try {
// Load Microsoft JDBC Driver 1.0
Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Obtaining a connection to SQL Server
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1269;"
+ "user=sa;password=HerongYang");
// Connection is ready to use
DatabaseMetaData meta = con.getMetaData();
System.out.println("Server name: "
+ meta.getDatabaseProductName());
System.out.println("Server version: "
+ meta.getDatabaseProductVersion());
// Closing the connection
con.close();
if (con.isClosed())
System.out.println("Connection closed.");
} catch (java.lang.ClassNotFoundException e) {
System.err.println("ClassNotFoundException: "
+e.getMessage());
} catch (SQLException e) {
System.err.println("SQLException: "
+e.getMessage());
}
}
}
推荐答案
扩展基类,它提供的东西是所有3个部分共享(编辑:像连接conn)
但是为什么要拆分?对我来说看起来很好。
Extend a base class, which provides the stuff that is shared by all 3 parts ( like the Connection "conn")
But why split that? Looks fine to me like it is.
在java中,将源代码拆分到不同文件中的唯一方法是代码是否存在于不同的类中。您可以编写具有在派生类(或类)中扩展的特定行为的基类。
In java, the only way to split source code in different files is if the code exists in different classes. You can write a base class with certain behavior that is extended in a derived class (or classes).
这篇关于打开和关闭不同类的连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文