JDBC相关配置和操作
获取数据库连接的几种方式
ps.数据库URL : String url = "jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC"
MySQL5.0-->driverClass="com.mysql.jdbc.Driver";
MySQL8.0-->driverClass="com.mysql.cj.jdbc.Driver";
通过Driver实例获取
//创建Driver对象
Driver driver = new Driver();
//数据库URL
String url = "jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC";
//Properties存放用户名和密码
Properties prop = new Properties();
prop.setProperty("user", "user1");
prop.setProperty("password", "102850");
//调用connect(),传入url和prop
Connection connect = driver.connect(url, prop);
//获得连接
System.out.println(connect);
通过DriverManager获取
public class Jdbc8Test01 {
// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC";
// 数据库的用户名与密码
static final String USER = "root";
static final String PASS = "102850";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
} catch (Exception se) {
// 处理 JDBC 错误
se.printStackTrace();
}// 处理 Class.forName 错误
finally {
// 关闭资源
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}// 什么都不做
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
从配置文件获取信息
配置文件内容
user=root
password=102850
url=jdbc:mysql://localhost:3306/dailytext?useSSL=false&serverTimezone=UTC
#MySQL8.0以上版本 JDBC 驱动名
driverClass=com.mysql.cj.jdbc.Driver
#MySQL8.0以下版本 JDBC 驱动名
#driverClass=com.mysql.jdbc.Driver
- 实例代码
//获取输入流(两种方法)
InputStream is = Jtest01.class.getClassLoader().getResourceAsStream("jdbc.properties");
//main方法中文件路径为Project下
FileInputStream fis = new FileInputStream("TEST02\\src\\jdbc.properties"); Properties prop = new Properties();
prop.load(fis); //获取配置信息
String user = prop.getProperty("user");
String password = prop.getProperty("password");
String url = prop.getProperty("url");
String driverClass = prop.getProperty("driverClass"); //注册驱动
Class.forName(driverClass); //获得Connection对象,建立与数据库的连接
Connection connection1 = DriverManager.getConnection(url, user, password);
Connection connection2 = DriverManager.getConnection(url, prop); System.out.println(connection1);
System.out.println(connection2);
druid数据库连接池
配置文件druid.proterties
url=jdbc:mysql://localhost:3306/dailytext?serverTimezone=UTC
username=user1
password=102850
driverClassName=com.mysql.cj.jdbc.Driver
initialSiize=10
maxActive=10
代码实现
//从数据库连接池获取连接
Properties prop = new Properties();
//ClassLoader.getSystemClassLoader().getResourceAsStream("String pathName")
// 此种方式读取文件位置默认为src目录下(在main方法和在@Test方法中路径一样)
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("Resource\\druid.properties");
//FileInputStream("String pathName")
// 在main方法中,此种方式读取文件位置默认为Project目录下
// 在@Test方法中,此种方式读取文件位置默认为Module目录下
// FileInputStream is = new FileInputStream("JDBC\\src\\Resource\\druid.properties");
prop.load(is);
DataSource source = DruidDataSourceFactory.createDataSource(prop);
Connection conn = source.getConnection();
System.out.println(conn);
PreparedStatement对比Statement的优点
(好处是基于PreparedStatement的预编译SQL语句功能)
- 解决SQL语句拼串的问题
- 解决SQL注入问题
- 实现对Blob类型的字段操作
- 提高批量操作时的效率
对数据库执行操作
步骤
1.创建文件输入流,从配置文件读取配置信息,
①.文件输入流位于main方法中时文件读取位置在Project目录下
②.文件输入流位于@Test方法中时文件读取位置在Module目录下
2.传入文件流
3.读取配置信息
4.加载JDBC驱动
5.通过DriverManager创建connection对象,获取数据库连接
6.编写SQL语句,使用占位符
7.创建statement(PreparedStatement)对象,传入SQL语句进行预编译
8.填充占位符
9.执行SQL操作
10.关闭资源
示例代码
public static void main(String[] args) {
FileInputStream fis = null;
Connection conn = null;
PreparedStatement pst = null;
try {
//获取文件输入流(main方法中文件位置在当前Project下)
fis = new FileInputStream("JDBC\\jdbc.properties");
//传入文件流
Properties prop = new Properties();
prop.load(fis);
//读取配置信息
String url = prop.getProperty("url");
String driverClass = prop.getProperty("driverClass");
System.out.println(url);
System.out.println(driverClass);
//加载JDBC驱动
Class.forName(driverClass);
//获取数据库连接
conn = DriverManager.getConnection(url, prop);
System.out.println(conn);
//预编译SQL语句
//String sql = "INSERT INTO person(`name`,`age`,`gender`,`birthday`)VALUES(?,?,?,?)";
String sql = "update person set `name`=? where `name`=?";
pst = conn.prepareStatement(sql);
//填充占位符
pst.setString(1, "Eclipse");
pst.setString(2, "Idea");
//执行操作(Insert;Update;Delete)
boolean execute = pst.execute();
System.out.println(execute);
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
try {
if (pst!=null)
pst.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (conn!=null)
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
if (fis!=null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JDBC相关配置和操作的更多相关文章
- 阿里云ECS服务器相关配置以及操作---上(初学者)
最近买了一台阿里云的ECS服务器 linux系统 centos镜像,把我相关的一些操作记录下来,供大家参考,不足之处欢迎指正. 首先买的过程就不用介绍了,根据自己的实际需要选择自己想要的配置,点击付钱 ...
- CentOS 配置防火墙操作实例(启、停、开、闭端口)CentOS Linux-FTP/对外开放端口(接口)TomCat相关
链接地址:http://blog.csdn.net/jemlee2002/article/details/7042991 CentOS 配置防火墙操作实例(启.停.开.闭端口): 注:防火墙的基本操作 ...
- Tomcat是什么:Tomcat与Java技、Tomcat与Web应用以及Tomcat基本框架及相关配置
1.Tomcat是什么 Apache Tomcat是由Apache Software Foundation(ASF)开发的一个开源Java WEB应用服务器. 类似功能的还有:Jetty. ...
- 20、Springboot 与数据访问(JDBC/自动配置)
简介: 对于数据访问层,无论是SQL还是NOSQL,Spring Boot默认采用整合 Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置.引入 各种xxxTemplate,x ...
- dbcp相关配置
最近在看一些dbcp的相关内容,顺便做一下记录,免得自己给忘记了. 1. 引入dbcp (选择1.4) <dependency> <groupId>com.alibaba. ...
- Tomcat中相关配置详解
tomcat的相关配置 server.xml <Server port="8005" shutdown="SHUTDOWN"> <!-- 属性 ...
- Spring Boot框架 - 数据访问 - JDBC&自动配置
一.新建Spring Boot 工程 特殊勾选数据库相关两个依赖 Mysql Driver — 数据库驱动 Spring Data JDBC 二.配置文件application.properties ...
- Mybatis-Generator相关配置demo
generatorConfig.xml配置信息 首先在resource中配置好datasource.propertise文件,包括数据库信息和mysql-connector的jar包位置. <? ...
- 【Spring】Spring的数据库开发 - 1、Spring JDBC的配置和Spring JdbcTemplate的解析
Spring JDBC 文章目录 Spring JDBC Spring JdbcTemplate的解析 Spring JDBC的配置 简单记录-Java EE企业级应用开发教程(Spring+Spri ...
随机推荐
- Python中并发、多线程等
1.基本概念 并发和并行的区别: 1)并行,parallel 同时做某些事,可以互不干扰的同一时刻做几件事.(解决并发的一种方法) 高速公路多个车道,车辆都在跑.同一时刻. 2)并发 concurre ...
- 正则表达式-Python实现
1.概述: Regular Expression.缩写regex,regexp,R等: 正则表达式是文本处理极为重要的工具.用它可以对字符串按照某种规则进行检索,替换. Shell编程和高级编程语言中 ...
- 得分(JAVA语言)
package 第三章习题; /* * 给出一个由O和X组成的串(长度为1~80),统计得分. * 每个O得分为目前连续出现的O的个数,X得分为0. * 例如,OOXXOXXOOO的得分为 * ...
- Git 上传项目到 Github
Git 上传项目到 Github 该文章主要讲解Git 上传项目到 Github,Gitee同理 配置Git 下载.安装Git 下载后一路(傻瓜式安装)直接安装即可 如果第一次使用git的话,需要设置 ...
- 教你如何用Python模拟http请求(GET,POST)
模拟http请求有什么用呢? 我们现在使用的所有需要使用网络的:软件 应用 app 网站里面的绝大部分功能都是通过http协议来工作的 什么是http协议? http协议,超文本传输协议(HTTP,H ...
- Android Studio 待看博文
•前言 学习过程中找到的一些好的博文,有些可能当时就看完了并解决了我的问题,有些可能需要好几天的事件才能消化. 特此记录,方便查阅. •CSDN 给新人的一些基础常识 TextView的文字长度测量及 ...
- 启用reuse_port参数让Nginx性能提升3倍
为什么启用 reuse_port 记得 2008 年做性能测试的时候,新进7台 lenovo 4核4G 服务器用于性能测试. 当时资源紧张,这7台服务器都装了双系统(Win2003/CentOS5)空 ...
- 使用ffmpeg 操作音频文件前后部分静音移除.
指令特别简单, 但是却琢磨了一下午. 总结看文档时要细心, 主要ffmpeg的版本要 8.2.1 以上 ffmpeg -i in.mp3 -af silenceremove=start_periods ...
- 201871030125-王芬 实验三 结对项目—《D{0-1}KP 实例数据集算法实验平台》项目报告
实验三 软件工程结对项目 项目 内容 课程班级博客链接 https://edu.cnblogs.com/campus/xbsf/2018CST 这个作业要求链接 https://www.cnblogs ...
- CTF导引(一)
ctf预备知识: 视频:https://www.bilibili.com/video/av62214776?from=search&seid=1436604431801225989 CTF比赛 ...