from:http://www.zekkocho.com/java/91-connect-to-database-with-jdbc-singleton
——————————————————————DBConnect.java—————————————————————
package Jdbc;
import java.sql.*;
public class DBConnect{
//Static instance of connection, only one will ever exist
private static Connection connection = null;
//Returns single instance of connection
public static Connection getConnection(){
//If instance has not been created yet, create it
if(DBConnect.connection == null){
initConnection();
}
return DBConnect.connection;
}
//Gets JDBC connection instance
private static void initConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/test";
String user = "root";
String pw = "";
DBConnect.connection =
DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (Exception e){
}
}
}
————————————————————————TestDB.java————————————————————————
package Jdbc;
import java.sql.*;
public class TestDB {
public static void main(String args[])
throws Exception{
//Always returns the same instance
Connection connection = DBConnect.getConnection();
ResultSet rows = null;
Statement s = connection.createStatement();
String select = "select * from people;";
rows = s.executeQuery(select);
while(rows.next()){
System.out.println(rows.getString("name"));
}
//Get connection again, still same instance
Connection connection2 = DBConnect.getConnection();
if(connection2 == connection){
System.out.println("Same Instance");
}
}
}
———————————————————new a test db:test————————————————
create table people(
id int,
name varchar(10)
);
mysql> insert into people values(1, "zhangsan");
Query OK, 1 row affected (0.04 sec)
mysql> insert into people values(2, "lisi");
Query OK, 1 row affected (0.02 sec)
mysql> insert into people values(1, "zhangsan");
Query OK, 1 row affected (0.02 sec)
mysql> select * from people;
+------+----------+
| id | name |
+------+----------+
| 1 | zhangsan |
| 2 | lisi |
| 1 | zhangsan |
+------+----------+
3 rows in set (0.00 sec)
mysql>
———————————————————————run result:——————————————————————
zhangsan
lisi
zhangsan
Same Instance
C:\Users\decli\Desktop\Jdbc>dir
驱动器 C 中的卷没有标签。
卷的序列号是 5EEE-076C
C:\Users\decli\Desktop\Jdbc 的目录
2011/10/31 09:49 <DIR> .
2011/10/31 09:49 <DIR> ..
2011/10/30 18:51 505 createDB.txt
2011/10/30 18:37 985 DBConnect.java
2011/10/31 10:34 <DIR> Jdbc
2011/10/30 18:39 679 TestDB.java
3 个文件 2,169 字节
3 个目录 35,813,437,440 可用字节
C:\Users\decli\Desktop\Jdbc>javac -d . *.java
C:\Users\decli\Desktop\Jdbc>C:\Users\decli\Desktop\java>java -cp .;./Jdbc/mysql-connector-java-5.0.8-bin.jar Jdbc.TestDB
zhangsan
lisi
zhangsan
Same Instance
注:如果是linux,请将 ; 换成 :即可:
gs_decli_0_231:/data/decli/java/testdb # java -cp .:./mysql-connector-java-5.0.8-bin.jar Jdbc.TestDB
zhangsan
lisi
zhangsan
Same Instance
gs_decli_0_231:/data/decli/java/testdb #