栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JDBC连接数据库的操作步骤

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JDBC连接数据库的操作步骤

JDBC连接数据库的步骤

  1. 将数据库的驱动加载到JVM中来
Class.forName("com.mysql.cj.jdbc.Driver");
  1. 创建数据库的连接
String url="jdbc:mysql://localhost:3306/test?useSSL=true&serverTimezone=UTC&characterEncoding=utf-8";
Connection conn=DriverManager.getConnection(url,"root","****");
  1. 要想执行sql语句,必须获得java.sql.Statement实例
Statement stm = conn.creatStatement();
  1. 执行sql语句
    Statement接口提供了三个sql语句操作的方法:
    executeQuery(String str) :执行sql查询语句的操作,返回一个结果集
    executeUpdate(String str) :执行增删改的操作,返回一个整数,代表本次操作影响到的记录数
    execute(String str):
ResultSet rs = stm.executeQuery();
int rows =stm.executeUpdate();
boolean bool = stm.execute();
  1. 关闭JDBC
    先关闭ResultSet;
    再关闭Statement;
    最后关闭连接对象connection;
if(rs != null){//关闭ResultSet
	try{
		rs.close();
	}catch(SQLException e){
		e.printStackTrace();
	}
}if(stm !=null){//关闭Statement
	try{
		stm.close();
	}catch(SQLException e){
		e.printStackTrace();
	}
}if(conn != null){//关闭connection
	try{
		conn.close();
	}catch(SQLException e){
		e.printStackTrace();
	}
	
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691182.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号