Java DataBase Connectivity Java数据库连接,Java语言操作数据库
步骤:
代码实现:
public class JdbcDemo02 {
public static void main(String[] args) {
Connection conn = null;
Statement stat = null;
//1.导入jar包(之前已经导入过就无需再进行导入操作)
try {
//2.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取Connection连接对象
conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "xxzjwnx");
//4.写入sql语句
String sql = "insert into account values (3,'wangwu',3000)";
//5.获取sql执行的对象Statement
stat = conn.createStatement();
//6.执行sql语句
int result = stat.executeUpdate(sql); //处理结果后影响的行数
System.out.println(result);
if(result>0){
System.out.println("添加成功");
}else {
System.out.println("添加失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(stat != null){
try {
stat.close();
} catch (SQLException e) {
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
注册驱动:告诉程序该使用哪一个数据库驱动jar
static void registerpriver(Driver driver):注册与给定的驱动程序 DriverManager。
写代码使用:class.forName(“com.mysq1.jdbc.Driver”);
通过查看源码发现:在com.mysq1.jdbc.Driver类中存在静态代码块
static {
try {
java.sql.DriverManager.registerpriver(new Driver());
}catch(SQLException E){
throw new RuntimeException("can't register driver!");
}
}
注意:mysq15之后的驱动jar包可以省略注册驱动的步骤。
获取数据库连接
//account表中修改记录
public class JdbcDemo03 {
public static void main(String[] args) {
Connection conn = null;
Statement stat =null;
try {
//1.驱动注册
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "xxzjwnx");
//3.定义sql语句
String sql = "update account set balance = 1000 where id = 1";
//4.获取执行sql对象Statement
stat = conn.createStatement();
//5.执行sql语句
int result = stat.executeUpdate(sql); //返回sql语句中影响最终结果的行数
System.out.println(result);
if(result>0){
System.out.println("修改成功");
}else {
System.out.println("添加失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
//这是新建文件jdbc.properties的代码
url=jdbc:mysql:///db2
user=root
password=xxzjwnx
driver=com.mysql.jdbc.Driver
//工具类代码的实现
public class JdbcUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/*
文件的读取,只需要读取一次即可拿到这些值,使用静态代码块
*/
static {
try {
//读取资源文件,获取值
//1.创建Properties集合类
Properties pro = new Properties();
//获取src路径下的文件的方式---->ClassLoader类加载器
ClassLoader classLoader = JdbcUtils.class.getClassLoader();
URL resource = classLoader.getResource("jdbc.properties");
String path = resource.getPath();
//2.进行加载文件
//pro.load(new FileReader("E:\\IDE_WorkPlace\\jdbc_learn\\01_jdbc\\src\\jdbc.properties"));
pro.load(new FileReader(path));
//3.获取值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获取连接的方法
* return 连接对象
* */
public static Connection getConnection2() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//对释放资源的方法(抛出异常的方法)进行简化
public static void close(ResultSet rs, Statement stat, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class JdbcUtils {
//定义初始化变量
private static DataSource ds;
//定义一个静态模块
static {
try {
//加载配置文件
Properties pro = new Properties();
InputStream is = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection2() throws SQLException {
return ds.getConnection();
}
//定义一个关闭流的方法
public static void closePool(Statement stat,Connection conn){
closePool(null,stat,conn);
}
public static void closePool(ResultSet rs, Statement stst, Connection conn){
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stst != null) {
try {
stst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) { //归还连接
e.printStackTrace();
}
}
}
//获取连接方法
public static DataSource getDataSource() {
return ds;
}
}
public class JdbcTemplateDemo02 {
/*
使用Test注解的方法进行书写,可以在一个类中不使用主方法的情况下独立执行并测试
*/
//添加一条记录
@Test
public void test1(){
JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
String sql = "insert into account values (null,?,?)";
template.update(sql,"tianqi",1500);
}
//删除刚刚添加的记录
@Test
public void test2(){
JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
template.update("delete from account where balance = 1500");
}
//查询id为3的记录,将其封装位Map
//注意查询的结果集长度只能为1,将列名作为key,将行表作为value
@Test
public void test3() {
JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
String sql = "select * from account where id = 1";
Map<String, Object> map = template.queryForMap(sql);
System.out.println(map); //{id=1, Name=zhangsan, balance=500}
}
//查询表中的所有记录
@Test
public void test4() {
JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
String sql = "select * from account";
List<Map<String, Object>> list = template.queryForList(sql);
System.out.println(list);
}
//使用template中的query()方法来进行查询表中的所有记录
@Test
public void test5() {
JdbcTemplate template = new JdbcTemplate(JdbcUtils.getDataSource());
String sql = "select * from account";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
}