1. 原理
由JAVA程序规定一套接口规范,让不同的的数据库商实现
不同的数据库商实现对应的接口、驱动
JDBC是java提供一套用于数据库操作的接口API,java程序员只需要面向这套接口的编程即可
2. JDBC编写步骤
- 注册驱动 --加载Driver类
- 获取连接–得到Connetion类
- 执行增删改查–发送SQL给 Mysql执行
- 释放资源–关闭相关连接
Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动,自动注册Driver
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);//获取连接
//3.操作数据库,实现增删改查
Statement stmt = conn.createStatement();//Statement对象可对表进行增删改查
3. 表的增删改查
//删除
static public void delete(Connection conn) throws SQLException {
String s="delete from stu where sno = '01'";
PreparedStatement ptmt=conn.prepareStatement(s);
ptmt.execute();
}
//添加
static public void add(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
String sql="insert into stu values('02','秋婷')";
String sql2="insert into stu values('03','世枫')";
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
}
//更新
static public void update(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
String sql="update stu set sno ='01' where sname = '秋婷'";
String sql2="update stu set sno ='02' where sname = '世枫'";
// stmt.executeBatch();
stmt.executeUpdate(sql);
stmt.executeUpdate(sql2);
}
//查询
static public void research(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from stu where sno = '01'");
while(rs.next()){
System.out.println(rs.getString(1 )+" "+rs.getString(2));
}
}
//输出
static void info(Connection conn) throws SQLException {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM stu");//返回查询的结果集--可看作一张表
//如果有数据,rs.next()返回true
while(rs.next()){
System.out.println(rs.getString(1 )+" "+rs.getString(2));
}
}