编写简单配置类,一般是配置文件中
package jdbctest;
/***
* 数据库连接相关常量信息
* @author liuxch
* @date 20170307
*/
public class SQLContsants {
//数据库连接url
public final static String url= "jdbc:mysql://localhost:3306/landingbj?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&autoReconnect=true";
//数据库驱动名称
public final static String name= "com.mysql.jdbc.Driver";
//数据库用户名
public final static String user= "root";
//数据库密码
public final static String passwowd= "dir13652";
}
写一个简单的数据库连接类
package jdbctest;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* 数据库连接工具类
* @author liuxch
* @date 20170307
*/
public class DBUtils {
private Connection conn;
/**
* 获取数据库connection对象
* @return
*/
public Connection getConnecton(){
try {
Class.forName(SQLContsants.name);
conn = DriverManager.getConnection(SQLContsants.url, SQLContsants.user, SQLContsants.passwowd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/***
* 关闭conn对象
*/
public void closeConn(){
try {
if(this.conn!=null){
this.conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
编写一个测试数据库连接类
package jdbctest;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 测试数据库连接类
*
* @author landingbj
*
*/
public class TestDBUtils {
public static void main(String[] args) {
DBUtils dbutil = new DBUtils();
Connection conn = dbutil.getConnecton();
if (conn != null) {
System.out.println("数据库已经连接成功");
}
dbutil.closeConn();
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}