JDBC的一些简单通用代码
功能包括
- 连接数据库
- 查询操作
- 执行sql语句
- jdbc相关类的加载
- 关闭连接
- 获取数据库格式的当前时间
代码
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MysqlConnector {
Connection connection=null;//数据库的连接
Statement statement=null;//句柄
public MysqlConnector(){
isLoadingJDBCSucessed();
boolean isconnectiveSucessed=createConnection();
if(isconnectiveSucessed) {
System.out.println("数据库连接成功!");
}
else {
System.out.println("数据库连接失败!");
}
try {
createStatement();
System.out.println("句柄创建成功!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("句柄创建失败!");
}
}
boolean isLoadingJDBCSucessed() {//类的加载
try {
//驱动类com.mysql.jdbc.Driver
//就在 mysql-connector-java-5.0.8-bin.jar中
//如果忘记了第一个步骤的导包,就会抛出ClassNotFoundException
Class.forName("com.mysql.jdbc.Driver");
System.out.println("数据库驱动加载成功 !");
return true;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
boolean createConnection() {//建立数据库的连接
try {
connection=(Connection) DriverManager.getConnection("jdbc:mysql://localhost/数据库的名称?characterEncoding=UTF-8",
"root","你的密码");
return true;
}catch (SQLException e) {
// TODO: handle exception
return false;
}
}
public void createStatement() throws SQLException {//返回statement
statement=connection.createStatement();
}
public boolean excuteSqlStatement(String sql) {//执行sql语句
try {
if(statement!=null) {
statement.execute(sql);
System.out.println("执行sql语句成功!");
return true;
}
return false;
}catch (SQLException e) {
// TODO: handle exception
System.out.println("执行sql语句失败,报错了!");
e.printStackTrace();
return false;
}
}
public void closeConnection() {//关闭数据的连接
if(statement!=null) {
try {
statement.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
if(connection!=null) {
try {
connection.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public ResultSet getQueryResult(String sql) {//获取查询的结果
try {
ResultSet rs=statement.executeQuery(sql);
return rs;
}catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
//获取当前时间
public String getNowTime() {
Date time=new Date();
String nowTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time);
return nowTime;
}
}