一、下载JDBC驱动程序
www.mysql.com
www.oracle.cn
用mysql数据库下载MySQL,用Oracle数据库下载Oracle
二、导入jar包
1.移入jar包(可以建立jar文件夹方便看)复制进项目
2.项目-》file-》project structure
3.点进Modules->选中jar->apply->ok
出现这个就是导入成功
三、连接语句
新建一个jdbc.properties储存数据库基本信息
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3308/yuangong?useSSL=false&serverTimezone=Asia/Shanghai
username=root
password=3306
OperDatabase.java
import java.io.FileInputStream;
import java.sql.*;
import java.util.Properties;
public class OperDatabase implements IOperDatabase {
@Override
public Connection getConnection() {
Connection conn= null;//链接建立失败
try {
//从txt文件获取,配置文件.properties
String driver = "";
String url = "";
String username = "";
String password = "";
Properties pro = new Properties();//属性集对象
pro.load(new FileInputStream("src/database/jdbc.properties"));
driver = pro.getProperty("driver");
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
Class.forName(driver);
conn= DriverManager.getConnection(url,username,password);
}catch (Exception exp){
System.out.println("getConnection()"+exp);
}
return conn;//链接建立成功
}
@Override
public void closeAll(ResultSet re, Statement stmt, Connection conn, PreparedStatement ps) {
try {
//非空判断
if (re != null) {
re.close();
}
}catch (Exception exp){
System.out.println("关闭ResultSet异常"+exp);
}
try {
if (stmt != null) {
stmt.close();
}
}catch (Exception exp){
System.out.println("关闭Statement异常"+exp);
}
try {
if (conn != null) {
conn.close();
}
}catch (Exception exp){
System.out.println("关闭Connection异常"+exp);
}
try {
if (ps != null) {
ps.close();
}
}catch (Exception exp){
System.out.println("关闭PreparedStatement异常"+exp);
}
}
}
IOperDatabase.java
package database;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public interface IOperDatabase {
//数据库连接
Connection getConnection();
//数据库关闭
void closeAll(ResultSet re, Statement stmt, Connection conn, PreparedStatement ps);
}