2019.3.28 JDBC相关
JDBC(Java Data Base Connectivity)
JDBC是一组用Java编写的类和接口
- 使用JDBC的好处:
- 1.Java的开发人员完全不需要关心数据库的连接方式和实现手段
- 2.提高代码的可维护性,是一种组件化思想
- 3.代码的执行效率很高 速度很快
- JDBC的缺点
- 1.代码繁琐(最大毛病)
- 2.维护代价高
编写JDBC
增删改(都差不多 就写一个了)
1.获取连接
下面的四个信息,只有当开发者在更换数据库时候需要改,其他所有的都不需要改
String url = "jdbc:mysql://localhost:3306/j0302";
String username = "root";
String password = "1234";
String driver = "com.mysql.jdbc.Driver"; // 驱动
Student student = new Student();
student.setName("王五");
student.setAddress("上海");
Connection conn = null;
PreparedStatement stmt = null;
try {
//加载驱动
//Java反射技术
Class.forName(driver);
//创建一个数据库连接
conn = DriverManager.getConnection(url, username, password);
-
执行SQL语句
//正常sql
// stmt = conn.prepareStatement("insert into student values (null ,'lisi','beijing')");
//字符串拼接实现sql缺点:麻烦,难以维护;不安全,完全无法避免SQL注入
// stmt = conn.prepareStatement("insert into student values (null,'"+student.getName()+"','"+student.getName()+"')");
stmt = conn.prepareStatement("insert into student(name,address) values (?,?)");
//给上述sql的占位符赋值
stmt.setString(1,student.getName());
stmt.setString(2,student.getAddress());
//增删改都使用该方法
int i = stmt.executeUpdate();
//i代表这次sql语句执行
System.out.println(i);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//3.关闭资源
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
查
public class QueryClass {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/j0302";
String username = "root";
String password = "1234";
String driver = "com.mysql.jdbc.Driver";
//jdbc查询的写法
//jdbc查询的目的:就是为了获取相应对象的list
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
List<Student> list = new ArrayList();
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
String sql = "select * from student";
stmt = conn.prepareStatement(sql);
//执行查询返回一个结果集
rs = stmt.executeQuery();
//rs.next()用来获取下一行数据
while (rs.next()){
int sid = rs.getInt("sid");
System.out.println(sid);
String name = rs.getString("name");
System.out.println(name);
String address = rs.getString("address");
System.out.println(address);
//每次循环都要创建一个新的stu 用来存储数据
Student stu = new Student();
stu.setId(sid);
stu.setName(name);
stu.setAddress(address);
list.add(stu);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
工具及工程:
JDBC工程
链接:https://pan.baidu.com/s/1-aUnJ9udezZufcO8YT38hA
提取码:2e78
JDBC优化
链接:https://pan.baidu.com/s/1OR2zfxPvVgfk5WQZZ-C0Rw
提取码:zkv3