1. 通用数据库连接及操作
一般数据库连接信息存放在properties文件中
jdbc.drivers = oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:DataName
jdbc.username = dbuser
jdbc.password = password
链接数据库,进行操作
写法一:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@MyDbComputerNameOrIP:1521:DataName",sUsr,sPwd);
写法二:
Properties props = new Properties(); //从属性文件中读取连接信息
FileInpuStream in = new FileInputStream("database.properties");
props.load(in);
in.close();
String drivers = props.getProperty("jdbc.drivers ");
System.setProperty("jdbc.drivers ", drivers); //注册该驱动
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
Connection conn = DriverManager.getConnection(url, username, password); //建立数据库连接
try {
Statement stat = conn.createStatement(); //创建Statement对象
stat.execute(sql); //可以执行任何sql操作
ResultSet rs = stat.executeQuery(); //执行select sql操作
ResultSet rs = stat.executeUpdate(); //执行insert, update, delete sql操作
while (rs.next()) {rs.getString(1) //返回当前行第一列的值}
} finally {conn.close();}
2. PreparedStatement预备查询语句
当一个sql被反复执行,那么就不需要每次都创建这个查询信息,使用PreparedStatement来创建一次,然后根据每次输入的条件不同,进行操作
String sql = "select * from books where name = ? and price = ?";
PreparedStatement preStat = conn.perparedStatement(sql);
preStat.setString(1, "corejava");
preStat.setString(2, "1000");
3. 事务
conn.setAutoCommit(false);
conn.commit(); //执行完所有的操作之后调用
conn.rollback(); //出现错误调用
4. 高级连接管理
使用JNDI来建立数据库连接
Context ctx = new InitialContext();
DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/corejava");
Connection conn = ds.getConnection();
5. LDAP轻量级目录访问协议
Hashtable env = new Hashtable();
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
DirContext initial = new InitialDirContext(env);
DirContext context = (DirContext) initial.lookup("ldap://localhost:389"); //访问本地LDAP服务器