文章目录
一、准备工作
步骤一: 在项目中新建一个文件夹,把对应数据库连接的jar包放入(ctrl+v)。
步骤二:右键jar包—>Build Path—>Add to Build Path,将该jar包提到代码中以供使用。
二、DML通过Statement连接数据库
2.1加载驱动
//1--加载驱动
try {
Class.forName("com.mysql.cj.jdbc.driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
在代码处理中用try catch处理异常较多。
Mysql5.0加载驱动的语句为:com.mysql.jdbc.Driver
,而Mysql8.0的为:com.mysql.cj.jdbc.Driver
2.2 获得连接
String url = "jdbc:mysql://127.0.0.1:3306/test_demo?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Hongkong&allowPublicKeyRetrieval=true";
Connection con = null;
try {
con = DriverManager.getConnection(url,"root","123456");
} catch (SQLException e) {
e.printStackTrace();
}
- url是数据库的地址,
jdbc:mysql://
为协议名;127.0.0.1
是本机的主机号,这里也可以用localhost代替;:3306
为端口号test_domo
为数据库名;- ?后边为一些规则,如编码格式、时区等等,其中时区字段
serverTimezone=Hongkong
在Mysql8.0的连接中必须有;- getConnection()里面的3个参数依次为:数据库的地址、账户、密码。
2.3 获得状态集
//3--获得状态集statement
Statement st = null;
try {
st = con.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
2.4 执行DML语句
int result = -1;
String sql = "insert into new_table(id,name,age,gendar) value(21,'赵柳',18,'男') ";
try {
result = st.executeUpdate(sql);
System.out.println(result);
} catch (SQLException e) {
e.printStackTrace();
}
- executeUpdate方法返回的为改动的记录条数;
- sql语句的编写要符合sql语言的标准编写规范。
2.5 关闭
// 5--关闭
try {
st.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
con = null;
注意关闭的顺序为先开启的后关闭。
2.6 总览
至此,对Mysql的DML操作完成。
代码总览:
package package1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC01 {
public static void main(String[] args) {
// 1--加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mysql://127.0.0.1:3306/test_demo?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=Hongkong&allowPublicKeyRetrieval=true";
int result = -1;
String sql = "insert into new_table(id,name,age,gendar) value(22,'赵柳',18,'男') ";
Connection con = null;
Statement st = null;
try {
// 2--连接数据库
con = DriverManager.getConnection(url, "root", "123456");
// 3--获得状态集statement
st = con.createStatement();
// 4--执行DML语句
result = st.executeUpdate(sql);
System.out.println(result);
// 5--关闭
st.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
con = null;
}
}
执行结果:
1
此时输出为1,说明result的结果为1,即被执行了一次。
数据库获取到数据,添加成功。
三、DQL通过Statement连接数据库
【前面加载、连接数据库与DML一致,后边会有一个结果集的处理】
3.1 加载驱动
//1-- 加载驱动
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
e