最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
用单例模式实现的java连接MySql数据库
时间:2022-07-02 18:20:04 编辑:袖梨 来源:一聚教程网
package com.adrop.util;
import java.sql.*;
public class DBManager {
//用户名
private String user = "";
//密码
private String password = "";
//主机
private String host = "";
//数据库名字
private String database = "";
//private DBManager dbm=null;
/*
private String url="jdbc:mysql://"+host+"/"+"useUnicode=true&characterEncoding=GB2312";
*/
private String url ="";
private Connection con = null;
Statement stmt;
/**
* 私有的构造方法,保证外部不能实例化,只能由DBManager自己能提供自
* 己的实例,并且只能有一个。
* 根据主机、数据库名称、数据库用户名、数据库用户密码取得连接。
* @param host String
* @param database String
* @param user String
* @param password String
*/
private DBManager(String host, String database, String user, String password) {
this.host = host;
this.database = database;
this.user = user;
this.password = password;
//显示中文
this.url = "jdbc:mysql://" + host + "/" + database +
"?useUnicode=true&characterEncoding=GB2312";
try {
Class.forName("org.gjt.mm.mysql.Driver");
}
catch (ClassNotFoundException e) {
System.err.println("class not found:" + e.getMessage());
}
try {
con = DriverManager.getConnection(this.url, this.user, this.password);
//连接类型为ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch (SQLException a) {
System.err.println("sql exception:" + a.getMessage());
}
import java.sql.*;
public class DBManager {
//用户名
private String user = "";
//密码
private String password = "";
//主机
private String host = "";
//数据库名字
private String database = "";
//private DBManager dbm=null;
/*
private String url="jdbc:mysql://"+host+"/"+"useUnicode=true&characterEncoding=GB2312";
*/
private String url ="";
private Connection con = null;
Statement stmt;
/**
* 私有的构造方法,保证外部不能实例化,只能由DBManager自己能提供自
* 己的实例,并且只能有一个。
* 根据主机、数据库名称、数据库用户名、数据库用户密码取得连接。
* @param host String
* @param database String
* @param user String
* @param password String
*/
private DBManager(String host, String database, String user, String password) {
this.host = host;
this.database = database;
this.user = user;
this.password = password;
//显示中文
this.url = "jdbc:mysql://" + host + "/" + database +
"?useUnicode=true&characterEncoding=GB2312";
try {
Class.forName("org.gjt.mm.mysql.Driver");
}
catch (ClassNotFoundException e) {
System.err.println("class not found:" + e.getMessage());
}
try {
con = DriverManager.getConnection(this.url, this.user, this.password);
//连接类型为ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch (SQLException a) {
System.err.println("sql exception:" + a.getMessage());
}
相关文章
- 王者荣耀侦探能力大测试攻略 王者荣耀侦探能力大测试怎么过 11-22
- 无期迷途主线前瞻兑换码是什么 11-22
- 原神欧洛伦怎么培养 11-22
- 炉石传说网易云音乐联动怎么玩 11-22
- 永劫无间手游确幸转盘怎么样 11-22
- 无期迷途主线前瞻兑换码是什么 无期迷途主线前瞻直播兑换码介绍 11-22