一、下载mysql的JDBC驱动jar包。
地址:
MySQL :: MySQL Community DownloadsMySQL :: Download MySQL Connector/J (Archived Versions)MySQL :: MySQL Community Downloads
打开后是这样,Operating System选项选择Platform Independent,就是选择其他系统下载资源。下载的方式选择zip压缩包下载。
下载并解压后复制jar包
打开项目,新建一个目录,命名为libs。将复制的jar包粘贴进去
右键libs->添加为库
二、进入java代码的编写
JDBC编程六步:
1.注册驱动
2.获取Connection连接对象
3.获取Statement操作对象
4.编写SQL语句
5.处理查询结果集(只存在于查询语句中)
6.释放资源
(一),注册驱动
Driver driver =new com.mysql.cj.jdbc.Driver(); DriverManager.registerDriver(driver);//其中com.mysql.cj.jdbc是包名,使用其中的Driver()类。
(二),获取Connection连接对象
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/数据库名","用户名","密码");
(三),获取Statement操作对象
Statement stmt=conn.createStatement();
(四),编写SQL语句,记录并输出
String sql="update student set sage=43 where idstudent=3"; int count=stmt.executeUpdate(sql);//executeUpdate适用于增,删,改 //execute(sql)是大众语句 System.out.println("修改了"+count+"记录");此处以更新语句为例
(五)先不写,后面进行补充
(六)释放 资源
stmt.close();conn.close();注意释放的顺序,必须先小到大,以及try/catch异常环绕。
三、代码展示
public static void main(String[] args){
Connection conn=null;
Statement stmt=null;
try{//1.注册驱动
Driver driver =new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);
//2.获取连接对讲connection
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root");
///3.获取数据库操作对象statement
stmt=conn.createStatement();
// 4.执行SQL
String sql="update student set sage=43 where idstudent=3";
int count=stmt.executeUpdate(sql);
System.out.println("修改了"+count+"记录");
}catch(SQLException e){
e.printStackTrace();
}finally{
//5 释放
if(stmt!=null){
try{
stmt.close();}catch(SQLException e){
e.printStackTrace();
}
}
if(conn!=null){
try{conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
运行成功后打开数据库表,将会看到表数据被更新。
四、结语
在学习过程中有遇到报错,修改成功但没及时记录,若遇到问题,请到评论区留言。