1)、JDBC API 中定义了 Connection 接口,用来表示与底层数据源的链接,JDBC 应用有两种方式获取 Connection 对象
1、DriverManager
// 获取Connection对象
Connection connection = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis","sa", "");
2、DataSource:
// 创建DataSource实例
DataSource dataSource = new UnpooledDataSource("org.hsqldb.jdbcDriver", "jdbc:hsqldb:mem:mybatis", "sa", "");
// 获取Connection对象
Connection connection = dataSource.getConnection();
2)、JDBC API 中定义了两个 DataSource 比较重要的扩展,用于支撑企业级应用
1)、通过 Statement 执行 Sql 语句
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from user");
1)、通过 ResultSet 处理查询结果集
// 遍历ResultSet
ResultSetMetaData metaData = resultSet.getMetaData();
int columCount = metaData.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= columCount; i++) {
String columName = metaData.getColumnName(i);
String columVal = resultSet.getString(columName);
System.out.println(columName + ":" + columVal);
}
System.out.println("---------------------------------------");
}
1)、代码示例
package com.blog4java.jdbc;
import com.blog4java.common.DbUtils;
import com.blog4java.common.IOUtils;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSource;
import org.junit.Test;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Example02 {
@Test
public void testJdbc() {
// 初始化数据
DbUtils.initData();
try {
// 1、创建DataSource实例
DataSource dataSource = new UnpooledDataSource("org.hsqldb.jdbcDriver",
"jdbc:hsqldb:mem:mybatis", "sa", "");
///2、获取Connection对象
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("select * from user");
///3、遍历ResultSet
ResultSetMetaData metaData = resultSet.getMetaData();
int columCount = metaData.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= columCount; i++) {
String columName = metaData.getColumnName(i);
String columVal = resultSet.getString(columName);
System.out.println(columName + ":" + columVal);
}
System.out.println("---------------------------------------");
}
///4、关闭连接
IOUtils.closeQuietly(statement);
IOUtils.closeQuietly(connection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class JDBCDriver implements Driver {
public static final JDBCDriver driverInstance = new JDBCDriver();
static {
try {
DriverManager.registerDriver(driverInstance);
} catch (Exception var1) {
}
}
}
java -Djdbc.drivers=org.hsqldb.jdbc.JDBCDriver
public class DriverManager {
static {
loadInitialDrivers();
println("JDBC DriverManager initialized");
}
}
package com.blog4java.jndi;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
public class Example04 {
@Before
public void before() throws IOException {
DataSourceFactory dsf = new UnpooledDataSourceFactory();
Properties properties = new Properties();
InputStream configStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties");
properties.load(configStream);
dsf.setProperties(properties);
DataSource dataSource = dsf.getDataSource();
try {
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
jndiProps.put(Context.URL_PKG_PREFIXES, "org.apache.naming");
Context ctx = new InitialContext(jndiProps);
ctx.bind("java:TestDC", dataSource);
} catch (NamingException e) {
e.printStackTrace();
}
}
@Test
public void testJndi() {
try {
Properties jndiProps = new Properties();
jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
jndiProps.put(Context.URL_PKG_PREFIXES, "org.apache.naming");
Context ctx = new InitialContext(jndiProps);
DataSource dataSource = (DataSource) ctx.lookup("java:TestDC");
Connection conn = dataSource.getConnection();
Assert.assertNotNull(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis","sa", "");
Statement stmt = conn.createStatement();
// 获取Connection对象
Connection connection = dataSource.getConnection();
PreparedStatement stmt = connection.prepareStatement("insert into " +
"user(create_time, name, password, phone, nick_name) " +
"values(?,?,?,?,?);");
stmt.setString(1,"2010-10-24 10:20:30");
stmt.setString(2,"User1");
stmt.setString(3,"test");
stmt.setString(4,"18700001111");
stmt.setString(5,"User1");
Connection conn = DBUtil.getConnection();
CallableStatement cs = conn.prepareCall("call p1()");//call p1 -- 不带括号也行
cs.execute();
conn.close();
// 获取Connection对象
Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis",
"sa", "");
Statement stmt = conn.createStatement();
String sql = "insert into user(create_time, name, password, phone, nick_name) " +
"values('2010-10-24 10:20:30','User1','test','18700001111','User1');";
stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet genKeys = stmt.getGeneratedKeys();
if(genKeys.next()) {
System.out.println("自增长主键:" + genKeys.getInt(1));
}
// 获取Connection对象
Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis","sa", "");
Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("SELECT * FROM user where name = '" + name + "'");
rs.updateString("password",password);
rs.updateRow();
DataBaseMetaData 接口的方法可分为以下几类
package com.blog4java.jdbc;
import com.blog4java.common.IOUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
/**
* 获取数据库基本信息
*/
public class Example08 {
@Test
public void testDbMetaData() {
try {
Class.forName("org.hsqldb.jdbcDriver");
// 获取Connection对象
Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis",
"sa", "");
DatabaseMetaData dmd = conn.getMetaData();
System.out.println("数据库URL:" + dmd.getURL());
System.out.println("数据库用户名:" + dmd.getUserName());
System.out.println("数据库产品名:" + dmd.getDatabaseProductName());
System.out.println("数据库产品版本:" + dmd.getDatabaseProductVersion());
System.out.println("驱动主版本:" + dmd.getDriverMajorVersion());
System.out.println("驱动副版本:" + dmd.getDriverMinorVersion());
System.out.println("数据库供应商用于schema的首选术语:" + dmd.getSchemaTerm());
System.out.println("数据库供应商用于catalog的首选术语:" + dmd.getCatalogTerm());
System.out.println("数据库供应商用于procedure的首选术语:" + dmd.getProcedureTerm());
System.out.println("null值是否高排序:" + dmd.nullsAreSortedHigh());
System.out.println("null值是否低排序:" + dmd.nullsAreSortedLow());
System.out.println("数据库是否将表存储在本地文件中:" + dmd.usesLocalFiles());
System.out.println("数据库是否为每个表使用一个文件:" + dmd.usesLocalFilePerTable());
System.out.println("数据库SQL关键字:" + dmd.getSQLKeywords());
IOUtils.closeQuietly(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
1)、DEFAULT
2)、READ_UNCOMMITTED
3)、READ_COMMITED
4)、REPEATABLE_READ
5)、SERLALIZABLE
@Test
public void testSavePoint() {
try {
Class.forName("org.hsqldb.jdbcDriver");
// 获取Connection对象
Connection conn = DriverManager.getConnection("jdbc:hsqldb:mem:mybatis",
"sa", "");
String sql1 = "insert into user(create_time, name, password, phone, nick_name) " +
"values('2010-10-24 10:20:30','User1','test','18700001111','User1')";
String sql2 = "insert into user(create_time, name, password, phone, nick_name) " +
"values('2010-10-24 10:20:30','User2','test','18700001111','User2')";
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql1);
// 创建保存点
Savepoint savepoint = conn.setSavepoint("SP1");
stmt.executeUpdate(sql2);
// 回滚到保存点
conn.rollback(savepoint);
conn.commit();
ResultSet rs = conn.createStatement().executeQuery("select * from user ");
DbUtils.dumpRS(rs);
IOUtils.closeQuietly(stmt);
IOUtils.closeQuietly(conn);
} catch (Exception e) {
e.printStackTrace();
}
}