Java20 数据库编程
指定的套路。
20.1 JDBC简介
package java.sql
DriverManager类, Connection、Statement、PreparedStatement、ResultSet接口
JDBC-ODBC桥连接
JDBC连接
JDBC网络连接
JDBC协议连接
20.2 连接Oracle数据库
Oracle数据库(数据监听服务Listener、实例服务SID)
OracleOraDb11g_home1TNSListener
OracleServiceMLDN
ClassPath (JavaBuilderPath)
D:\app\mldn\product\11.2.0\dbhome_1\jdbc\lib\ojdbc6.jar;
package cn.mldn.demo public class JDBCDemo{ private static final String DATABASE_DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final String DATABASE_URL = "jdbc:oracle:thin:@localhost:1521:mldn"; private static final String DATABASE_USER = "scott"; private static final String DATABASE_PASSWORD = "tiger"; public static void main(String[] args){ Connection conn = null; Class.forName(DATABASE_DRIVER); //加载数据库驱动程序 conn = DriverManager.getConnection(DATABASE_URL,DATABASE_USER,DATABASE_PASSWORD); 14732 System.out.println(conn); conn.close(); } }
20.3 Statement数据操作接口
public Statement createStatement() throws SQLException;
Statement state = conn.createStatement(); String sql = ""; //insert into/delete/update → int count = state.executeUpdata(sql); System.out.println("更新操作系统的行数:"+count); //select → ResultSet result = state.executeQuery(sql); while(result.next()){ int nid = result.getInt("nid"); String title = result.getString(2); }
20.4 PreparedStatement数据操作接口
public PreparedStatement prepareStatement(String sql) throws SQLException
PreparedStatement pstate = conn.prepareStatement(sql); String sql = ""; String sql = "insert into news(nid,title,content,newsdate,writer) " +" values( ?,?,?,?,?)" ; pstate.setInt(1,05); pstate.setString(2,"重大新闻"); pstate.setString(3,"这是安康市的一则新闻"); pstate.setDate(4,"2021-4-6"); pstate.setString(5,"anzhong"); //insert into/delete/update → int count = state.executeUpdata(sql); System.out.println("更新操作系统的行数:"+count); //select → ResultSet result = state.executeQuery(sql); while(result.next()){ int nid = result.getInt("nid"); String title = result.getString(2); }
20.5 数据批处理
Statement statement = conn.createStatement();
statement.addBatch(sql);
statement.addBatch(sql);
statement.addBatch(sql);
int result[] = statement.executeBatch(); //执行批处理
System.out.println("批量更新结果:"+Arrays.toString(result));
conn.close();
程序执行结果:[1,1,1]
20.6 事务控制
try{
conn.commit();
}catch(SQLException e){
conn.rollback();
}