获取Connection的5种方式

//方式一 @Test public void test1() throws SQLException { //获取Driver实现类对象 Driver driver = new Driver(); //jdbc:mysql 协议 //localhost:ip地址 //zoo 数据库名 String url = "jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; //将用户名和密码封装在properties中 Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); Connection conn=driver.connect(url, info); System.out.println(conn); }
//方式2:在如下的程序中,不出先第三方的API,有可移植性 @Test public void test2() throws Exception { //使用反射获取Driver对象 com.mysql.cj.jdbc.Driver Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver = (Driver) clazz.newInstance(); //提供连接的数据库 String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; //提供需要的用户名和密码 Properties info=new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); Connection conn=driver.connect(url, info); System.out.println(conn); }
//方式3:使用DriverManager替换Driver @Test public void test3() throws Exception { //获取Driver实现类对象 Class clazz = Class.forName("com.mysql.cj.jdbc.Driver"); Driver driver =(Driver) clazz.newInstance(); //注册驱动 DriverManager.registerDriver(driver); String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; //获取连接 Connection connection = DriverManager.getConnection(url, "root", "root"); System.out.println(connection); }
//方式4:可以知识加载驱动,不要显示注册驱动了 @Test public void test4() throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/zoo?serverTimezone=UTC"; Connection connection = DriverManager.getConnection(url, "root", "root"); System.out.println(connection); } @Test public void test5() throws Exception { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306?serverTimezone=UTC", "root", "root"); System.out.println(connection); }
//方式5:将数据库连接需要的4个基本信息声明在配置文件中 @Test public void test6() throws Exception { //读取配置文件中的基本信息 InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); properties.load(is); String user = properties.getProperty("user"); String password = properties.getProperty("password"); String url = properties.getProperty("url"); String DrverClass = properties.getProperty("DrverClass"); Class.forName(DrverClass); Connection connection = DriverManager.getConnection(url, user, password); System.out.println(connection); }

 转载:https://blog.csdn.net/weixin_45371966/article/details/103549042

 
 

__EOF__

本文作者皮军旗
本文链接https://www.cnblogs.com/pijunqi/p/14131662.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   皮军旗  阅读(1245)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示