JDBC编程:通过java代码来操作mysql数据库
数据库编程 是需要 数据库服务器 提供一些API 供程序员调用的。
API:Application Programming Interface 应用程序 编程 接口
一组类/函数 给 程序员调用, 实现某些功能。
JDBC 通过 驱动程序(软件,转接头) 才能操作数据库
1.到中央仓库下载驱动包
2.将jar引入项目中
1)创建一个项目目录,然后把jar复制到当前的项目中
2)把这个目录标记成“库”
耦合和内聚
耦合:两个模块之间的关联关系是不是非常紧密,是不是这边的变化影响到另一边。
eg:小明的父母生病了,然后他推掉一切工作回去看父母,对我影响很大,这就叫高耦合。
小明的一个普通朋友生病了,它只是嘘寒问暖了一下,对我影响很小,这就叫低耦合。
写代码要追求低耦合,不然随便改个代码,就会引起其他模块出现bug。
** 内聚**:把相同的/相关联的功能放在一起,内聚就高;反之,到处放,内聚就低。
eg:小明把衣服到处扔,这就是低内聚。
小明把衣服整理好,放进衣柜,这就是高内聚。
我们追求高内聚和低耦合!
开始编写代码
1.创建DataSource
2.建立连接
3.构造sql语句
4.把sql发送给服务器,执行sql
5.关闭连接,释放资源。
插入(insert)、修改(update)、删除(delete)
public static void main(String[] args) throws SQLException {//显示处理受查异常
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学号:");
int id = scanner.nextInt();
System.out.println("请输入名字:");
String name = scanner.next();
//1.创建dataSource
DataSource dataSource = new MysqlDataSource();//来自于Mysql驱动包 向上转型
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Student?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");//用户名
((MysqlDataSource) dataSource).setPassword("1234");//自己的密码
//2.与数据库服务器建立连接 连接好之后, 才能进行请求-响应 交互
Connection connection = dataSource.getConnection();
//3.构造sql
String sql = "insert into student values (?,?)";//拼接sql
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);//第一个问号 id表示数据库里的列名
statement.setString(2,name);//第二个问号
//4.把sql发送给服务器 返回一个整数->影响的行数
int n = statement.executeUpdate();
System.out.println("n = " + n);
//关闭连接,释放资源,后获取的资源先释放
statement.close();
connection.close();
}
查询(select)
public static void main(String[] args) throws SQLException {
//1.创建dataSource
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/Student?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("1234");
//2.建立连接
Connection connection = dataSource.getConnection();
//3.创建mysql语句
String sql = "select *from student where name = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,"杜甫");//条件查询
//4.将sql传到服务器 返回的是一个集合 通过循环来遍历
ResultSet resultSet = statement.executeQuery();//用结果集合resultSet来接受
while(resultSet.next()) {//通过next获取到临时表的每一行数据
int id = resultSet.getInt("id");//列名 如果有别名就写别名
String name = resultSet.getString("name");
System.out.println("id = " + id + " " + "name = " + name);
}
//关闭连接,释放资源
resultSet.close();
statement.close();
connection.close();
}