Java JDBC 连接数据库 Demo

import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;

public class Dao {

protected Connection conn;
protected Statement stat;

private String url;
private String userName;
private String passWord;

// 默认构造函数,访问本机上的特定数据库
public Dao() {

//jdbc:oracle:thin:@localhost:1521:orcl
this.url = "jdbc:mysql://localhost:3306/world";
this.userName = "root";
this.passWord = "11191224";
}

// 用于访问指定数据库
public Dao(String url, String userName, String passWord) {
this.url = url;
this.userName = userName;
this.passWord = passWord;
}

// 开启conn以及stat 和关闭事物的自动提交
public void open() {
try {

//oracle.jdbc.driver.OracleDriver

Class.forName("com.mysql.jdbc.Driver");

this.conn = DriverManager.getConnection(this.url, this.userName,
this.passWord);
this.stat = conn.createStatement();
conn.setAutoCommit(false);

} catch (ClassNotFoundException e) {
System.out.println("请检查jar包是否导入");
} catch (SQLException e) {
e.printStackTrace();
}
}

// 返回stat对象
public Statement getStat() {
return this.stat;
}

// 返回conn对象
public Connection getConn() {
return this.conn;
}

// 关闭
public void close() {
if (this.stat != null) {
try {
stat.close();
} catch (SQLException e) {
}
}
if (this.conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}

public void commit() {
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}

public void rollback() {
try {
conn.rollback();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

原文地址:https://www.cnblogs.com/Dream-Lasting/p/4184376.html