1.概念
通过Java代码操作mysql数据库
数据库编程,是需要数据库服务器,提供一些API,供程序员调用的
2.安装
2.1下载
在程序中操作mysql需要先安装mysql的驱动包
并且要把驱动包引入到项目中
在中央仓库可以下载到驱动包(mvnrepository.com)
2.2jar如何引入项目中?
1.先把jar复制到当前项目的目录中
复制刚刚下载的那个jar包如何到刚刚的lib目录选中ctrl v粘贴
2.把这个目录标记成“库”
此时准备工作已经完成,可以开始编写代码了
3.编写代码
3.1.创建java类
3.2.创建Datasource
Datasource:描述:“数据源头”==>数据库服务器所在位置
Datasource可能有多个,选择javax.sql的
public class demo1 {public static void main(String[] args) {//1.创建datasourceDataSource dataSource = new MysqlDataSource();//向上转型((MysqlDataSource) dataSource).setUrl();// 向下转型}}
3.3URL
url是给jdbc操作mysql使用的
url形式:
Datasource光写url只是能找到mysql服务器了
但是还得认证(用户名,密码)
3.4建立和数据库服务器之间的连接
连接好了之后,才能进行后续的请求-响应 交互
要注意包的选择
//2。建立和数据库服务器之间的连接Connection connection = dataSource.getConnection();
问题:
解决方法:
3.5构造sql
//3.构造sqlString sql = "insert into student values(1, ' 张三')";PreparedStatement statement = connection.prepareStatement(sql);
3.6把sql发给服务器
返回值是一个整数,,表示影响到的行数
int n = statement.executeUpdate();
3.7执行完毕之后,关闭连接,释放资源
程序通过代码和服务器进行通信,是需要消耗一定的硬件和软件资源的
在程序结束时,就需要告知服务器,释放这些资源
释放顺序:后获取到的资源先释放
statement.close();connection.close();
4.插入,删除,修改代码
插入:
String sql = "insert into student values(1, ' 张三')";
PreparedStatement statement = connection.prepareStatement(sql);
删除:
String sql = "delete from student where id = 1";
PreparedStatement statement = connection.prepareStatement(sql);
修改:
String sql = "update student set name = '张三' where id = 100";
PreparedStatement statement = connection.prepareStatement(sql);
5.插入操作如何不写死
String sql = "insert into student values(1, ' 张三')";PreparedStatement statement = connection.prepareStatement(sql);
这里的张三写死了,我们不好去更改
6.代码
public class demo1 {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.创建datasourceDataSource dataSource = new MysqlDataSource();//向上转型((MysqlDataSource) dataSource).setUrl();// 向下转型((MysqlDataSource) dataSource).setUrl("root");((MysqlDataSource) dataSource).setPassword("kkkk");//2.建立和数据库服务器之间的连接Connection connection = dataSource.getConnection();//3.构造sqlString sql = "insert into student values(?, ?)";//String sql = "delete from student where id = 1";//String sql = "update student set name = '张三' where id = 100";PreparedStatement statement = connection.prepareStatement(sql);statement.setInt(1,id);statement.setString(2, name);//打印sql看效果System.out.println("sql = "+ statement);//4.把sql发给服务器int n = statement.executeUpdate();System.out.println("n = " + n);//5.释放资源,关闭连接statement.close();connection.close();}}