1.查询记录
try {
System.out.println("start");
//1.加载驱动类
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.获得连接 java.sql.connection
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","scott","0804");
System.out.println(con);
//3.执行sql语句 java.sql.Statement
Statement stmt = con.createStatement();
//4.执行sql查询语句 ---> 查询得到的是结果集java.sql.ResultSet
String sql = "select * from bbs_user";
ResultSet rs = stmt.executeQuery(sql);
System.out.println();
//5.访问结果集
while(rs.next()){
//System.out.println(rs.getInt(1)+","+rs.getString(2)+","+rs.getString(3)+","+rs.getString(4));
System.out.println(rs.getInt("id")+rs.getString("username")+rs.getString("userpass")+rs.getString("address"));
}
//6.关闭资源-->异常后面要细致处理
rs.close();
stmt.close();
con.close();
System.out.println("end");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
2.增删改的执行语句
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL","scott","0804");
Statement stmt = con.createStatement();
//增加一条记录
//String sql = "insert into bbs_user(id,username,userpass,address)"+"values(10003,'wangwu','12567','山东济南')";
//更新一条记录
//String sql = "update bbs_user set userpass='lspass' where id = 10002";
//删除记录
String sql = "delete bbs_user where id = 10002";
//返回的是影响的记录条数 查询一条记录是:stmt执行executeQuery()
int n = stmt.executeUpdate(sql);
System.out.println(n);
stmt.close();
con.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
3.封装方法
以下为datebase.properties
driverClass=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:ORCL
user=scott
pass=****
==========================
以下在JdbcUtil类中
private static Properties prop = new Properties();
static{
try {
prop.load(JdbcUtil.class.getResourceAsStream("/datebase.properties"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static Connection getConn(){
try {
Class.forName(prop.getProperty("driverClass"));
//System.out.println(Class.forName(prop.getProperty("driverClass")));
Connection con = DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("user"),prop.getProperty("pass"));
return con;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
4.使用封装方法,JdbcUtil是封装方法getConn()所在的类
//插入一条信息
private static void insertRow(){
try {
Connection con = JdbcUtil.getConn();
Statement stmt = con.createStatement();
//
int id = 10004;
String name = "zhaoliu";
String pass = "zliu";
String addr = "张家口";
String sql = "insert into bbs_user(id,username,userpass,address)"+"values("+id+",'"+name+"','"+pass+"','"+addr+"')";
int n = stmt.executeUpdate(sql);
System.out.println(n);
stmt.close();
con.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}