Granda's Blog

MySQL:JDBC开发

JDBC最基础编程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Test {
public static void main(String[] args) throws Exception{
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
try(
//使用DriverManager来获取数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/spring6","root","123456");
//使用Connection连接来创建一个Statement对象
Statement stat = conn.createStatement();
//执行sql语句
ResultSet rs = stat.executeQuery("select * from ssh_department")
)
{
while(rs.next()){
System.out.println(rs.getString(1)+"\t"+rs.getString(2));
}
}
}
}

使用配置文件mysql.ini

  • 配置文件内容

    1
    2
    3
    4
    driver:com.mysql.jdbc.Driver
    url:jdbc:mysql://127.0.0.1:3306/spring6
    username:root
    password:123456
  • 编程实例

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    public class Test {
    private String driver;
    private String url;
    private String username;
    private String password;
    public void initParam(String paramFile) throws Exception {
    // 使用Properties类来加载类属性文件
    Properties props = new Properties();
    props.load(new FileInputStream(paramFile));
    driver = props.getProperty("driver");
    url = props.getProperty("url");
    username = props.getProperty("username");
    password = props.getProperty("password");
    }
    public void creatTable(String sql) throws Exception {
    //加载驱动
    Class.forName(driver);
    try (
    //获取数据库连接
    Connection conn = DriverManager.getConnection(url, username, password);
    //创建Statement对象
    Statement stat = conn.createStatement()) {
    stat.executeUpdate(sql);
    }
    }
    public static void main(String[] args) throws Exception {
    Test test = new Test();
    test.initParam("mysql.ini");
    test.creatTable("create table student(" + "id int auto_increment primary key," + "name varchar(50));");
    System.out.println("建表成功");
    }
    }

JDBC的事务支持

  • 开启事务(关闭自动提交)

    conn.setAutoCommit(false);
    
  • 执行多条DML语句

    stmt.executeUpdate(...);
    stmt.executeUpdate(...);
    
  • 提交事务

    conn.commit();
    
  • 回滚事务

    conn.rollback();
    

C3P0连接池配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//创建连接池实例
ComboPooledDataSource ds = new ComboPooledDataSource();
//设置连接池实例需要的驱动
ds.setDriverClass("com.mysql.jdbc.Driver");
//设置数据库url
ds.setJdbcUrl("jdbc:mysql://localhost:3306/spring6");
//设置用户名
ds.setUser("root");
//设置密码
ds.setPassword("123456");
//设置连接池最大连接数
ds.setMaxPoolSize(40);
//设置连接池最小连接数
ds.setMinPoolSize(2);
//设置连接池的初始连接数
ds.setInitialPoolSize(10);
//设置连接池缓存的Statement的最大数量
ds.setMaxStatements(180);
  • 获得数据库连接

    Connection conn = ds.getConnection();