MySQL连接数据库的基本步骤:
/**
* @category 数据库连接器
* @function 负责数据库的链接、数据库资源的关闭处理
*/
package com.excelprocess.dbOper;
import java.sql.*;
public class DbConnector
{
private String host=null; //数据库主机
private String port=null; //数据库连接端口
private String dbName=null;//数据库名称
private String user=null; //登录账号
private String pw=null; //登录密码
private Connection ct=null; //数据库连接对象
/**
* @category 无参构造函数
*/
public DbConnector()
{
this.host="";//默认数据库主机,服务器:
this.port="3306";//默认数据库连接端口
this.dbName="数据库名";//默认连接数据库
this.user="root";//登录账号
this.pw="root";//登录密码
}
/**
* @category 有参构造函数
* @param host 数据库主机
* @param port 数据库连接端口
* @param dbName 数据库名称
* @param user 登录账号
* @param password 登录密码
*/
public DbConnector(String host,String port,String dbName,String user,String password){
this.host = host;
this.port = port;
this.dbName = dbName;
this.user = user;
this.pw = password;
}
/**
* @category 数据库连接函数
* @return 连接成功返回非空Connection对象,连接失败返回空Connection对象
*/
public Connection getConnection()
{
String url="jdbc:mysql://"+this.host+":"+this.port+"/"+this.dbName+"?user="+this.user+"&password="+this.pw
+"&useUnicode=true&characterEncoding=utf-8";
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
if(ct == null){//获取数据库连接对象
ct=DriverManager.getConnection(url);
System.out.println("数据库连接资源connection已打开!");
}
} catch (Exception e) {
e.printStackTrace();
}
return ct;
}
/**
* @category 数据库资源关闭函数
* @param ct Connection类的对象
* @param sm Statement类的对象
* @param rs ResultSet类的对象
* @return 数据库资源关闭成功返回true,否则返回false
*/
public boolean close_db(Connection ct,Statement sm,ResultSet rs)
{
boolean b=false;
try{
if(rs!=null){
rs.close();
rs=null;
}
if(sm!=null){
sm.close();
sm=null;
}
if(ct!=null){
ct.close();
ct=null;
}
if(rs==null && sm==null && ct==null)
{
b=true;
}
}catch(Exception ex){
ex.printStackTrace();
}
return b;
}
/**
* @category 数据库资源关闭函数
* @param ct Connection类的对象
* @param ps PreparedStatement类的对象
* @param rs ResultSet类的对象
* @return 数据库资源关闭成功返回true,否则返回false
*/
public boolean close_db(Connection ct,PreparedStatement ps,ResultSet rs)
{
boolean b=false;
try{
if(rs!=null){
rs.close();
rs=null;
}
if(ps!=null){
ps.close();
ps=null;
}
if(ct!=null){
ct.close();
ct=null;
}
if(rs==null && ps==null && ct==null)
{
b=true;
}
}catch(Exception ex){
ex.printStackTrace();
}
return b;
}
/**
* @category 数据库资源关闭函数
* @param ct Connection类的对象
* @param ps PreparedStatement类的对象
* @return 数据库资源关闭成功返回true,否则返回false
*/
public boolean close_db(Connection ct,PreparedStatement ps)
{
boolean b=false;
try{
if(ps!=null){
ps.close();
ps=null;
}
if(ct!=null){
ct.close();
ct=null;
}
if(ps==null && ct==null)
{
b=true;
}
}catch(Exception ex){
ex.printStackTrace();
}
return b;
}
}