JDBC最基础编程
|
|
使用配置文件mysql.ini
配置文件内容
1234driver:com.mysql.jdbc.Driverurl:jdbc:mysql://127.0.0.1:3306/spring6username:rootpassword:123456编程实例
1234567891011121314151617181920212223242526272829303132333435public 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连接池配置
|
|
获得数据库连接
Connection conn = ds.getConnection();