连接MySQL的5种方式

数据大师
数据大师
数据大师
293
文章
0
评论
2021-08-2010:53:28 评论 58 4512字
摘要

今天为大家分享Java中连接数据库(本文演示使用的是MySQL数据库,其他关系型数据库类似)常用的5种方式,读者可以自行比较优缺点,在实际项目开发或学习研究中采用其中一种即可!

 

首先,需要导入相关jar包。 这里是5种连接方式jar包的总和,按项目实际需要添加即可。截图如下:

连接MySQL的5种方式

 

一、直接代码连接

 

测试代码如下:

public class TestConnByJDBC {public static void main(String[] args) throws SQLException {Connection conn = null;String driver = "com.mysql.cj.jdbc.Driver";String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC";String username = "root";String password = "root";try {Class.forName(driver);conn = DriverManager.getConnection(url, username, password);System.out.println("TestConnectionByJDBC success");conn.close();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}效果图:

连接MySQL的5种方式

 

二、读取属性文件

 

在src下新建属性文件jdbc.properties,并加入以下内容:

driver =com.mysql.cj.jdbc.Driverurl =jdbc:mysql://localhost:3306/test?serverTimezone=UTCusername =rootpassword =root

测试代码如下:

 

public class TestConnByPropertiesFile {public static void main(String[] args) throws IOException, ClassNotFoundException {InputStream in = TestConnByPropertiesFile.class.getClassLoader().getResourceAsStream("jdbc.properties");Properties pt = new Properties();pt.load(in);String driver = pt.getProperty("driver");String url = pt.getProperty("url");String username = pt.getProperty("username");String password = pt.getProperty("password");Connection conn = null;Class.forName(driver);try {conn = DriverManager.getConnection(url, username, password);System.out.println("TestConnectionByPropertiesFile success");conn.close();}catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}效果图:

连接MySQL的5种方式

 

三、C3p0配置

 

在src下新建配置文件c3p0-config.xml,并加入以下内容:

<?xml version="1.0" encoding="UTF-8"?><c3p0-config><named-config name="myTest"><property name="user">root</property><property name="password">root</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/test?serverTimezone=UTC</property><property name="driverClass">com.mysql.cj.jdbc.Driver</property><property name="acquireIncrement">5</property><property name="initialPoolSize">20</property><property name="maxPoolSize">25</property><property name="minPoolSize">5</property></named-config></c3p0-config>测试代码如下:

public class TestConnByC3P0Conf {private static ComboPooledDataSource cpds;static {cpds = new ComboPooledDataSource("myTest");}public static DataSource getDataSource() {return cpds;}public static Connection getConnection() throws SQLException {return cpds.getConnection();}public static void main(String[] args) throws Exception{Connection connection = TestConnByC3P0Conf.getConnection();System.out.println(connection);}}效果图:

连接MySQL的5种方式

 

四、使用MyBatis

 

在src下新建配置文件MyBatisconfig.xml,并加入如下内容:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC" /><property name="username" value="root" /><property name="password" value="root" /></dataSource></environment></environments></configuration>测试代码如下:

public class TestConnByMyBatis {public static void main(String[] args) {String resource = "./src/MyBatisconfig.xml";InputStream is = null;try {is = new FileInputStream(resource);} catch (FileNotFoundException e) {e.printStackTrace();}SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);SqlSession session = sessionFactory.openSession();System.out.println(session.getConnection());}}效果图:

连接MySQL的5种方式

 

五、使用Hibernate

 

在src下新建配置文件hibernate.cfg.xml,并加入如下内容:

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory><property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property><property name="connection.url">jdbc:mysql://localhost:3306/test?serverTimezone=UTC</property><property name="connection.username">root</property><property name="connection.password">root</property><property name="connection.pool_size">2</property><property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property><property name="show_sql">true</property><property name="hbm2ddl.auto">create</property></session-factory></hibernate-configuration>测试代码如下:

public class TestConnByHibernate {public static void main(String[] args) {Configuration configure = new Configuration().configure();SessionFactory factory = configure.buildSessionFactory();Session session = factory.openSession();System.out.println(session.connection());}}效果图:

连接MySQL的5种方式

 

至此,我们学会了连接数据库的各种方式!

 

End.

作者:丿SeeYouAgain

本文为转载分享,如果涉及作品、版权和其他问题,请联系我们第一时间删除(微信号:lovedata0520)

更多文章前往首页浏览http://www.itongji.cn/

 

  • 我的微信公众号
  • 微信扫一扫
  • weinxin
  • 我的微信公众号
  • 微信扫一扫
  • weinxin
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: