JDBC操作数据步骤
1.加载驱动(驱动数据库:有三种方式,常用反射加载)
2.获取连接对象(建立从java到数据库的连接通道)
3.获取处理命令的对象(通过连接对象想数据发送并执行sql语句)
4.执行sql操作
5.处理结果
6.资源关闭
实际操纵如下:
insert添加操作:
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456");
//3.获取处理命令的对象
String sql = "insert into dept(dno,dname,tel) values(1,'市场部','111')";
PreparedStatement ps = conn.prepareStatement(sql);
//4.执行sql操作
int i = ps.executeUpdate();
//5.处理结果
if(i){
System.out.println("执行成功,影响数据行数:"+i);
}
//6.资源关闭
stat.close();
conn.close();
delete删除操作:
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456");
//3.获取处理命令的对象
String sql = "delete from dept where dno=1";
PreparedStatement ps = conn.prepareStatement(sql);
//4.执行sql操作
int i = ps.executeUpdate();
//5.处理结果
if(i>0){
System.out.println("执行成功,影响数据行数:"+i);
}
//6.资源关闭
stat.close();
conn.close();
update修改操作:
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456");
//3.获取处理命令的对象
String sql = "update dept set tel='123456' where dno=2";
PreparedStatement ps = conn.prepareStatement(sql);
//4.执行sql操作
int i = ps.executeUpdate();
//5.处理结果
if(i>0){
System.out.println("执行成功,影响数据行数:"+i);
}
//6.资源关闭
stat.close();
conn.close();
select查询操作:
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "123456");
System.out.println(conn);
//3.获取处理命令的对象
String sql = "select dname as name,dno as no,tel as phone from dept";
PreparedStatement ps = conn.prepareStatement(sql);
//4.执行sql操作
ResultSet rs = ps.executeQuery();
//5.处理结果
while(rs.next()){
//已经获取一行数据
String name = rs.getString("name");
int sno = rs.getInt("sno");
String tel = rs.getString("phone");
System.out.println(sno+"/"+name+"/"+tel);
}
//6.资源关闭
stat.close();
conn.close();