没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
试读
2页
JDBC Java Database Connectivity,简称JDBC,是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法 JDBC连接MySQL数据库的几种方式 方式一:创建Driver()对象 @Test public void test1() throws SQLException { Driver driver = new com.mysql.cj.jdbc.Driver(); //jdbc:mysql:协议 localhost:ip地址 3306:端口号 mt:数据库名 ?serverTimezon
资源详情
资源评论
资源推荐
JDBC技术技术(一一):如何通过:如何通过JDBC连接连接MySQL数据库数据库
JDBC
Java Database Connectivity,简称JDBC,是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸
如查询和更新数据库中数据的方法
JDBC连接连接MySQL数据库的几种方式数据库的几种方式
方式一:创建Driver()对象
@Test
public void test1() throws SQLException {
Driver driver = new com.mysql.cj.jdbc.Driver();
//jdbc:mysql:协议 localhost:ip地址 3306:端口号 mt:数据库名 ?serverTimezone=UTC设置时区,否则报错
String url = "jdbc:mysql://localhost:3306/mt?serverTimezone=UTC";
//将用户名和密码封装在Properties中
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "写你自己数据库密码");
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
方式二: 通过反射获取Driver()对象,好处是不会出现第三方API
@Test
public void test2() throws Exception {
//1. 获取Driver实现类的对象: 使用反射
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2. 提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/mt?serverTimezone=UTC";
//3. 提供要连接的用户名和密码
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "写你自己数据库密码");
//4. 获取连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
方式三:使用DriverManger替代Driver
@Test
public void test3() throws Exception {
//1. 获取Driver的实现类对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
//2. 提供连接信息
String url = "jdbc:mysql://localhost:3306/mt?serverTimezone=UTC";
String user = "root";
String password = "写你自己数据库密码";
//3.注册驱动
DriverManager.registerDriver(driver);
//4.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
方式四:可以只加载驱动,不再显示注册驱动
@Test
public void test4() throws Exception {
//1. 提供连接信息
String url = "jdbc:mysql://localhost:3306/mt?serverTimezone=UTC";
String user = "root";
String password = "写你自己数据库密码";
//2. 加载Driver
weixin_38595243
- 粉丝: 7
- 资源: 898
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论10