- IDEA项目src目录下创建包,里面创建Java类(demo02.java):
package com.reviewjdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
public class demo02 {
//数据库地址
private static String dbUrl = "jdbc:mysql://localhost:3306/db_book";
//用户名
private static String dbUserName = "root";
//密码
private static String dbPassword = "123456";
//驱动名称
private static String jdbcName = "com.mysql.jdbc.Driver";
public static void main(String[] args) {
/** 1.
* 加载数据驱动
*/
try {
Class.forName(jdbcName);
System.out.println("驱动加载成功.");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败.");
}
/** 2.
* 获取数据库连接
*/
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
System.out.println("获取数据库连接成功!");
System.out.println("进行数据库操作.");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}