Java数据库连接技术

Posted coshaho

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java数据库连接技术相关的知识,希望对你有一定的参考价值。

使用mysql作为开发数据库,创建user表。创表语句如下:

create database learn;
use learn;
CREATE TABLE user(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(32), age INT);
INSERT INTO user(NAME, age) VALUES(\'coshaho\', 29);
INSERT INTO user(NAME, age) VALUES(\'cauchy\', 29);

一、使用Java直接连接mysql

1、添加mysql驱动

      <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.13</version>
    </dependency>

2、连接代码如下

package com.coshaho.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Java连接数据库
 * @author coshaho
 */
public class MysqlConnector 
{
    public static void main(String[] args)
    {
        Connection con = null;
        Statement statement = null;
        ResultSet rs = null;
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://132.232.35.119:3306/learn";
        String user = "root";
        String password = "root";
        try 
        {
            Class.forName(driver);
            // 使用DriverManager获取连接
            con = DriverManager.getConnection(url,user,password);
            // 创建statement类对象,用来执行SQL语句!!
            statement = con.createStatement();
            String sql = "select * from user";
            rs = statement.executeQuery(sql);
            System.out.println("name" + "\\t" + "age");  
             
            int age = 0;
            String name = null;
            while(rs.next())
            {
                // ResultSet获取返回值时,列名不区分大小写
                name = rs.getString("nAme");
                age = rs.getInt("age");
                System.out.println(name + "\\t" + age);
            }
        } 
        catch(ClassNotFoundException e) 
        {   
            e.printStackTrace();   
        } 
        catch(SQLException e) 
        {
            e.printStackTrace();  
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        finally
        {
            // 从内向外释放连接
            try 
            {
                if(null != rs)
                {
                    rs.close();
                }
            } 
            catch (SQLException e) 
            {
                e.printStackTrace();
            }
            try 
            {
                if(null != statement)
                {
                    statement.close();
                }
            } 
            catch (SQLException e) 
            {
                e.printStackTrace();
            }
            try 
            {
                if(null != con)
                {
                    con.close();
                }
            } 
            catch (SQLException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

3、执行效果

二、使用连接池连接数据库

这里以C3p0连接池作为样例,连接池里的连接使用完后,需要主动释放。

1、maven配置如下。

    <!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>

2、C3p0配置文件名字必须为c3p0-config.xml,并且放到classpath下。

<?xml version="1.0" encoding="UTF-8"?>

<c3p0-config>
    <!-- 默认C3p0配置 -->
    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://132.232.35.119:3306/learn</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>

    <!--以name为标识的数据源 -->
    <named-config name="mysql">
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://132.232.35.119:3306/learn</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="acquireIncrement">5</property>
        <property name="initialPoolSize">10</property>
        <property name="minPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </named-config>
</c3p0-config>

3、测试代码

package com.coshaho.datasource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * C3p0连接池
 * @author coshaho
 */
public class C3p0DataSource 
{
    private static ComboPooledDataSource ds = new ComboPooledDataSource("MySQL");
    
    
    public static Connection getConnection() throws SQLException
    {
        return ds.getConnection();
    }
    
    /**
                * 需要主动释放连接,这里调用的close方法并非关闭连接,而是归还到连接池
     * @param conn
     * @param st
     * @param rs
     */
    public static void release(Connection conn,Statement st,ResultSet rs)
    {
        if(null != rs)
        {
            try
            {
                rs.close();
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
        if(null != st)
        {
            try
            {
                st.close();
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
        
        if(null != conn)
        {
            try
            {
                conn.close();
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args)
    {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        try
        {
            conn = C3p0DataSource.getConnection();
            String sql = "insert into user(name, age) values(?, ?)";
            st = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            st.setString(1, "hkx");
            st.setInt(2, 30);
            st.executeUpdate();
            // 获取数据库自动生成的主键
            rs = st.getGeneratedKeys();
            if(rs.next()){
                System.out.println(rs.getInt(1));
            }
        }
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        finally
        {
            C3p0DataSource.release(conn, st, rs);
        }
    }
}

三、Spring与C3p0整合

spring集成c3p0,实际上,就是让spring初始化c3p0实例,并用jdbcTemplate管理。这里需要注意的是,使用jdbcTemplate直接执行sql,不需要手动释放连接,jdbcTemplate已经帮你自动释放连接了。 

1、spring maven配置

      <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.4.RELEASE</version>
    </dependency>

2、spring文件配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- 引入jdbc配置文件 -->   
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 使用spring初始化DataSource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    
    <!-- 使用JdbcTemplate封装DataSource -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://132.232.35.119:3306/learn
jdbc.user=root
jdbc.password=root

3、测试代码

package com.coshaho.datasource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class SpringJdbcTest 
{
    private static ApplicationContext context;
    public static void main(String[] args)
    {
        String xmlpath = "spring.xml";
        context = new ClassPathXmlApplicationContext(xmlpath);
        JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
        jdbcTemplate.update("insert into user(name, age) values (?, ?)", 
                "Jack", 20);
    }
}

 

以上是关于Java数据库连接技术的主要内容,如果未能解决你的问题,请参考以下文章

如何在片段中使用 GetJsonFromUrlTask​​.java

网络技术理论:包片段帧数据报和段

错误:E/RecyclerView:未连接适配器;跳过片段上的布局

网络技术理论:包片段帧数据报和段

使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段

java 为啥要实现 function?